@meghjs/mcp 0.0.0-stage → 0.7.0

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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/docs/advanced/caching.md +72 -0
  6. package/dist/docs/advanced/database.md +328 -0
  7. package/dist/docs/advanced/events.md +169 -0
  8. package/dist/docs/advanced/file-uploads.md +141 -0
  9. package/dist/docs/advanced/health.md +81 -0
  10. package/dist/docs/advanced/logging.md +96 -0
  11. package/dist/docs/advanced/mail.md +439 -0
  12. package/dist/docs/advanced/orm/migrations.md +210 -0
  13. package/dist/docs/advanced/orm/models.md +291 -0
  14. package/dist/docs/advanced/orm/queries.md +169 -0
  15. package/dist/docs/advanced/orm/query-builder.md +120 -0
  16. package/dist/docs/advanced/orm/relations.md +179 -0
  17. package/dist/docs/advanced/orm/seeding.md +129 -0
  18. package/dist/docs/advanced/orm.md +145 -0
  19. package/dist/docs/advanced/plugins.md +90 -0
  20. package/dist/docs/advanced/queue.md +217 -0
  21. package/dist/docs/advanced/scheduler.md +253 -0
  22. package/dist/docs/advanced/testing.md +257 -0
  23. package/dist/docs/advanced/views.md +335 -0
  24. package/dist/docs/ai/mcp.md +162 -0
  25. package/dist/docs/cli/basic.md +133 -0
  26. package/dist/docs/cli/database.md +112 -0
  27. package/dist/docs/cli/generators.md +605 -0
  28. package/dist/docs/cli/scaffold/auth.md +172 -0
  29. package/dist/docs/cli/scaffold/domains.md +224 -0
  30. package/dist/docs/cli/scaffold/index.md +77 -0
  31. package/dist/docs/cli/scaffold/rbac.md +118 -0
  32. package/dist/docs/cli/scaffold/templates.md +235 -0
  33. package/dist/docs/core-concept/authentication.md +162 -0
  34. package/dist/docs/core-concept/configuration.md +268 -0
  35. package/dist/docs/core-concept/controller.md +350 -0
  36. package/dist/docs/core-concept/dependency-injection.md +213 -0
  37. package/dist/docs/core-concept/error-handling.md +185 -0
  38. package/dist/docs/core-concept/middleware.md +143 -0
  39. package/dist/docs/core-concept/request-context.md +110 -0
  40. package/dist/docs/core-concept/validation.md +355 -0
  41. package/dist/docs/getting-started/application.md +233 -0
  42. package/dist/docs/getting-started/installation.md +166 -0
  43. package/dist/docs/getting-started/introduction.md +136 -0
  44. package/dist/docs/getting-started/upgrading-0.4.md +125 -0
  45. package/dist/docs/getting-started/upgrading-0.5.md +293 -0
  46. package/dist/docs/getting-started/upgrading-0.6.md +251 -0
  47. package/dist/docs/getting-started/upgrading-0.7.md +225 -0
  48. package/dist/docs/getting-started/upgrading-megh.md +91 -0
  49. package/dist/docs/getting-started/upgrading-next.md +12 -0
  50. package/dist/docs/getting-started/upgrading.md +137 -0
  51. package/dist/docs/getting-started/usage.md +194 -0
  52. package/dist/docs/index.md +58 -0
  53. package/dist/docs/microservices/openapi.md +387 -0
  54. package/dist/docs/microservices/websocket.md +165 -0
  55. package/dist/docs/production/deployment.md +256 -0
  56. package/dist/docs/production/security.md +307 -0
  57. package/dist/docs/reference/api.md +999 -0
  58. package/dist/docs/reference/faq.md +227 -0
  59. package/dist/docs/reference/versioning.md +105 -0
  60. package/dist/docs.d.ts +30 -0
  61. package/dist/docs.js +126 -0
  62. package/dist/index.d.ts +10 -0
  63. package/dist/index.js +22 -0
  64. package/dist/megh.d.ts +59 -0
  65. package/dist/megh.js +207 -0
  66. package/dist/prompts.d.ts +3 -0
  67. package/dist/prompts.js +47 -0
  68. package/dist/result.d.ts +18 -0
  69. package/dist/result.js +48 -0
  70. package/dist/server.d.ts +17 -0
  71. package/dist/server.js +40 -0
  72. package/dist/tools/context.d.ts +11 -0
  73. package/dist/tools/context.js +2 -0
  74. package/dist/tools/database.d.ts +8 -0
  75. package/dist/tools/database.js +58 -0
  76. package/dist/tools/docs.d.ts +3 -0
  77. package/dist/tools/docs.js +63 -0
  78. package/dist/tools/generate.d.ts +10 -0
  79. package/dist/tools/generate.js +177 -0
  80. package/dist/tools/project.d.ts +3 -0
  81. package/dist/tools/project.js +84 -0
  82. package/dist/version.d.ts +2 -0
  83. package/dist/version.js +10 -0
  84. package/package.json +58 -4
package/dist/megh.js ADDED
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolveProject = resolveProject;
7
+ exports.cliBin = cliBin;
8
+ exports.tscBin = tscBin;
9
+ exports.runNode = runNode;
10
+ exports.runMegh = runMegh;
11
+ exports.parseJsonOutput = parseJsonOutput;
12
+ exports.isProduction = isProduction;
13
+ exports.readPackageJson = readPackageJson;
14
+ exports.projectInfo = projectInfo;
15
+ exports.projectStructure = projectStructure;
16
+ const child_process_1 = require("child_process");
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const path_1 = __importDefault(require("path"));
19
+ const cli_1 = require("@meghjs/cli");
20
+ /** How long one CLI call may run before it is killed. */
21
+ const TIMEOUT_MS = 300_000;
22
+ // eslint-disable-next-line no-control-regex
23
+ const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
24
+ /**
25
+ * Resolve the project a tool works on: the given directory, else the server's
26
+ * default (`MEGH_PROJECT_ROOT` or the directory it was started in). Walks up
27
+ * to the nearest `package.json`, like the CLI does.
28
+ */
29
+ function resolveProject(cwd, fallback) {
30
+ const start = path_1.default.resolve(fallback, cwd ?? ".");
31
+ const root = (0, cli_1.findProjectRoot)(start);
32
+ if (!root)
33
+ throw new Error(`No package.json found in ${start} or any parent directory.`);
34
+ return root;
35
+ }
36
+ /** Resolve `<pkg>/<file>` from the project first, then from this package. */
37
+ function resolveFrom(root, pkg, file) {
38
+ for (const paths of [[root], [__dirname]]) {
39
+ try {
40
+ const pkgJson = require.resolve(`${pkg}/package.json`, { paths });
41
+ const target = path_1.default.join(path_1.default.dirname(pkgJson), file);
42
+ if (fs_1.default.existsSync(target))
43
+ return target;
44
+ }
45
+ catch {
46
+ // not installed there; try the next location
47
+ }
48
+ }
49
+ return null;
50
+ }
51
+ /**
52
+ * The `megh` executable to run. Prefers the CLI installed in the project, so
53
+ * its version matches the project's `@meghjs/core`, and falls back to the one
54
+ * this package depends on.
55
+ */
56
+ function cliBin(root) {
57
+ const bin = resolveFrom(root, "@meghjs/cli", path_1.default.join("dist", "bin.js"));
58
+ if (!bin)
59
+ throw new Error("Could not find @meghjs/cli. Install it in the project: npm i -D @meghjs/cli");
60
+ return bin;
61
+ }
62
+ /** The project's TypeScript compiler (`typescript/bin/tsc`). */
63
+ function tscBin(root) {
64
+ const bin = resolveFrom(root, "typescript", path_1.default.join("bin", "tsc"));
65
+ if (!bin)
66
+ throw new Error("Could not find typescript. Install it in the project: npm i -D typescript");
67
+ return bin;
68
+ }
69
+ /**
70
+ * Run a Node.js script in `root` and capture its output. It runs in its own
71
+ * process: its console output must not reach the server's stdout, which
72
+ * carries the MCP protocol. stdin is closed so a prompt cannot hang the call.
73
+ */
74
+ function runNode(root, script, args) {
75
+ return new Promise((resolve, reject) => {
76
+ const child = (0, child_process_1.spawn)(process.execPath, [script, ...args], {
77
+ cwd: root,
78
+ env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0", CI: "1" },
79
+ stdio: ["ignore", "pipe", "pipe"],
80
+ timeout: TIMEOUT_MS,
81
+ windowsHide: true,
82
+ });
83
+ let stdout = "";
84
+ let stderr = "";
85
+ child.stdout.setEncoding("utf8").on("data", (d) => (stdout += d));
86
+ child.stderr.setEncoding("utf8").on("data", (d) => (stderr += d));
87
+ child.on("error", reject);
88
+ child.on("close", (code, signal) => {
89
+ if (signal)
90
+ stderr += `\n${path_1.default.basename(script)} was stopped (${signal}) after ${TIMEOUT_MS / 1000}s.`;
91
+ resolve({ exitCode: code ?? 1, stdout: stdout.replace(ANSI, ""), stderr: stderr.replace(ANSI, "") });
92
+ });
93
+ });
94
+ }
95
+ /** Run `megh <args>` in `root`. */
96
+ function runMegh(root, args) {
97
+ return runNode(root, cliBin(root), args);
98
+ }
99
+ /** Parse JSON a command printed with `--json`, ignoring any lines logged before it. */
100
+ function parseJsonOutput(stdout) {
101
+ const start = stdout.search(/^[[{]/m);
102
+ if (start < 0)
103
+ throw new Error(`Expected JSON output, got:\n${stdout}`);
104
+ return JSON.parse(stdout.slice(start));
105
+ }
106
+ /**
107
+ * Whether the project runs with `NODE_ENV=production`, from the server's
108
+ * environment or the project's `.env` (which the CLI also loads).
109
+ */
110
+ function isProduction(root) {
111
+ if (process.env.NODE_ENV)
112
+ return process.env.NODE_ENV === "production";
113
+ const envFile = path_1.default.join(root, ".env");
114
+ if (!fs_1.default.existsSync(envFile))
115
+ return false;
116
+ const line = fs_1.default
117
+ .readFileSync(envFile, "utf8")
118
+ .split(/\r?\n/)
119
+ .find((l) => /^\s*NODE_ENV\s*=/.test(l));
120
+ return !!line && line.split("=")[1].trim().replace(/^["']|["']$/g, "") === "production";
121
+ }
122
+ function readPackageJson(root) {
123
+ return JSON.parse(fs_1.default.readFileSync(path_1.default.join(root, "package.json"), "utf8"));
124
+ }
125
+ /** The `@meghjs/*` packages a project depends on and the `megh` settings in its package.json. */
126
+ function projectInfo(root) {
127
+ const pkg = readPackageJson(root);
128
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
129
+ const megh = Object.fromEntries(Object.entries(deps).filter(([name]) => name.startsWith("@meghjs/")));
130
+ const installed = {};
131
+ for (const name of Object.keys(megh)) {
132
+ try {
133
+ const file = require.resolve(`${name}/package.json`, { paths: [root] });
134
+ installed[name] = JSON.parse(fs_1.default.readFileSync(file, "utf8")).version ?? null;
135
+ }
136
+ catch {
137
+ installed[name] = null;
138
+ }
139
+ }
140
+ return {
141
+ root,
142
+ name: pkg.name ?? null,
143
+ version: pkg.version ?? null,
144
+ isMeghProject: "@meghjs/core" in deps,
145
+ meghDependencies: megh,
146
+ installedVersions: installed,
147
+ scripts: pkg.scripts ?? {},
148
+ meghConfig: pkg.megh ?? null,
149
+ hasEnvFile: fs_1.default.existsSync(path_1.default.join(root, ".env")),
150
+ production: isProduction(root),
151
+ };
152
+ }
153
+ /**
154
+ * File suffixes the `megh` generators write, by kind. Migrations are matched
155
+ * by folder instead, since their names are `<timestamp>_<name>.ts`.
156
+ */
157
+ const KINDS = [
158
+ ["controllers", ".controller.ts"],
159
+ ["services", ".service.ts"],
160
+ ["models", ".model.ts"],
161
+ ["dtos", ".dto.ts"],
162
+ ["configs", ".config.ts"],
163
+ ["middlewares", ".middleware.ts"],
164
+ ["mails", ".mail.ts"],
165
+ ["events", ".event.ts"],
166
+ ["listeners", ".listener.ts"],
167
+ ["queues", ".queue.ts"],
168
+ ["workers", ".worker.ts"],
169
+ ["tasks", ".task.ts"],
170
+ ["seeders", ".seeder.ts"],
171
+ ["factories", ".factory.ts"],
172
+ ["tests", ".spec.ts"],
173
+ ["tests", ".test.ts"],
174
+ ];
175
+ /** The project's source files grouped by what they are (controllers, models, ...). */
176
+ function projectStructure(root) {
177
+ const src = path_1.default.join(root, "src");
178
+ const groups = {};
179
+ const add = (kind, file) => (groups[kind] ??= []).push(file);
180
+ const walk = (dir) => {
181
+ if (!fs_1.default.existsSync(dir))
182
+ return;
183
+ for (const e of fs_1.default.readdirSync(dir, { withFileTypes: true })) {
184
+ if (e.name === "node_modules" || e.name.startsWith("."))
185
+ continue;
186
+ const full = path_1.default.join(dir, e.name);
187
+ if (e.isDirectory()) {
188
+ walk(full);
189
+ continue;
190
+ }
191
+ const rel = path_1.default.relative(root, full).split(path_1.default.sep).join("/");
192
+ const kind = KINDS.find(([, suffix]) => e.name.endsWith(suffix))?.[0];
193
+ if (kind)
194
+ add(kind, rel);
195
+ else if (/\/database\/migrations\//.test(`/${rel}`))
196
+ add("migrations", rel);
197
+ else
198
+ add("other", rel);
199
+ }
200
+ };
201
+ walk(src);
202
+ walk(path_1.default.join(root, "tests"));
203
+ for (const files of Object.values(groups))
204
+ files.sort();
205
+ const entry = ["src/app.ts", "src/main.ts", "src/server.ts", "src/index.ts"].find((f) => fs_1.default.existsSync(path_1.default.join(root, f)));
206
+ return { root, entry: entry ?? null, counts: Object.fromEntries(Object.entries(groups).map(([k, v]) => [k, v.length])), files: groups };
207
+ }
@@ -0,0 +1,3 @@
1
+ import type { ToolContext } from "./tools/context";
2
+ /** Prompts that walk an assistant through common Megh tasks with the server's tools. */
3
+ export declare function registerPrompts({ server, readOnly }: ToolContext): void;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerPrompts = registerPrompts;
4
+ const zod_1 = require("zod");
5
+ const user = (text) => ({ messages: [{ role: "user", content: { type: "text", text } }] });
6
+ /** Prompts that walk an assistant through common Megh tasks with the server's tools. */
7
+ function registerPrompts({ server, readOnly }) {
8
+ server.registerPrompt("megh-review-project", {
9
+ title: "Review this Megh project",
10
+ description: "Check the project's setup, routes and structure, and point out problems.",
11
+ }, () => user([
12
+ "Review this Megh application.",
13
+ "1. Call megh_project_info and megh_doctor. Report any failed or warning checks and how to fix them.",
14
+ "2. Call megh_project_structure and megh_list_routes. Summarize the API: resources, routes and what each controller does.",
15
+ "3. Call megh_typecheck and report any type errors.",
16
+ "4. Look for problems: controllers without services, models without migrations, routes with no validation DTO.",
17
+ "When you're unsure how Megh does something, check with megh_search_docs before suggesting a change.",
18
+ ].join("\n")));
19
+ server.registerPrompt("megh-explain", {
20
+ title: "Explain a Megh feature",
21
+ description: "Explain a Megh feature from the docs, with an example that fits this project.",
22
+ argsSchema: { topic: zod_1.z.string().describe("The feature, e.g. validation, queues, relations, authentication.") },
23
+ }, ({ topic }) => user(`Explain how ${topic} works in Megh. Search the docs with megh_search_docs, read the most relevant pages with megh_read_doc, ` +
24
+ "and answer from them, with a short code example. Use names from this project (see megh_project_structure) where it helps. " +
25
+ "Say so if the docs don't cover something instead of guessing."));
26
+ if (readOnly)
27
+ return;
28
+ server.registerPrompt("megh-add-resource", {
29
+ title: "Add a REST resource",
30
+ description: "Create a table, model and CRUD API for a new resource, then check it compiles.",
31
+ argsSchema: {
32
+ name: zod_1.z.string().describe("Resource name, e.g. Product."),
33
+ fields: zod_1.z
34
+ .string()
35
+ .optional()
36
+ .describe('Columns, e.g. "title,price:money,status:in(draft|live)". Omit to choose them from a template.'),
37
+ },
38
+ }, ({ name, fields }) => user([
39
+ `Add a REST resource called ${name} to this Megh application.`,
40
+ fields
41
+ ? `1. Call megh_make with kind "resource", name "${name}" and fields "${fields}".`
42
+ : `1. Call megh_list_templates to find a template that fits ${name}; if one does, use it, otherwise pick sensible fields. Then call megh_make with kind "resource".`,
43
+ "2. Call megh_migrate to create the table (skip this if it is refused, and say so).",
44
+ "3. Call megh_list_routes with static true to confirm the new routes, and megh_typecheck to confirm it compiles.",
45
+ "4. Summarize the files written and the routes added.",
46
+ ].join("\n")));
47
+ }
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ import { type CliResult } from "./megh";
3
+ export type ToolResult = {
4
+ content: {
5
+ type: "text";
6
+ text: string;
7
+ }[];
8
+ isError?: boolean;
9
+ };
10
+ export declare function truncate(s: string, max?: number): string;
11
+ export declare const text: (value: unknown, isError?: boolean) => ToolResult;
12
+ /** A CLI run as a tool result: its output, flagged as an error when it exited non-zero. */
13
+ export declare const fromCli: (r: CliResult) => ToolResult;
14
+ /** A `--json` CLI run as a tool result holding the parsed JSON. */
15
+ export declare const jsonFromCli: (r: CliResult) => ToolResult;
16
+ /** Report thrown errors to the client as a tool error instead of failing the request. */
17
+ export declare const safe: <A>(handler: (args: A) => Promise<ToolResult> | ToolResult) => (args: A) => Promise<ToolResult>;
18
+ export declare const cwdArg: z.ZodOptional<z.ZodString>;
package/dist/result.js ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cwdArg = exports.safe = exports.jsonFromCli = exports.fromCli = exports.text = void 0;
4
+ exports.truncate = truncate;
5
+ const zod_1 = require("zod");
6
+ const megh_1 = require("./megh");
7
+ /** Longest text a tool returns; longer output keeps its start and end. */
8
+ const MAX_TEXT = 40_000;
9
+ function truncate(s, max = MAX_TEXT) {
10
+ if (s.length <= max)
11
+ return s;
12
+ const half = Math.floor(max / 2);
13
+ return `${s.slice(0, half)}\n\n... ${s.length - max} characters omitted ...\n\n${s.slice(-half)}`;
14
+ }
15
+ const text = (value, isError = false) => ({
16
+ content: [{ type: "text", text: truncate(typeof value === "string" ? value : JSON.stringify(value, null, 2)) }],
17
+ ...(isError ? { isError } : {}),
18
+ });
19
+ exports.text = text;
20
+ /** A CLI run as a tool result: its output, flagged as an error when it exited non-zero. */
21
+ const fromCli = (r) => (0, exports.text)([r.stdout.trim(), r.stderr.trim()].filter(Boolean).join("\n\n") || "(no output)", r.exitCode !== 0);
22
+ exports.fromCli = fromCli;
23
+ /** A `--json` CLI run as a tool result holding the parsed JSON. */
24
+ const jsonFromCli = (r) => {
25
+ if (r.exitCode !== 0)
26
+ return (0, exports.fromCli)(r);
27
+ try {
28
+ return (0, exports.text)((0, megh_1.parseJsonOutput)(r.stdout));
29
+ }
30
+ catch {
31
+ return (0, exports.fromCli)(r);
32
+ }
33
+ };
34
+ exports.jsonFromCli = jsonFromCli;
35
+ /** Report thrown errors to the client as a tool error instead of failing the request. */
36
+ const safe = (handler) => async (args) => {
37
+ try {
38
+ return await handler(args);
39
+ }
40
+ catch (err) {
41
+ return (0, exports.text)(err instanceof Error ? err.message : String(err), true);
42
+ }
43
+ };
44
+ exports.safe = safe;
45
+ exports.cwdArg = zod_1.z
46
+ .string()
47
+ .optional()
48
+ .describe("Project directory (absolute, or relative to the server's project). Defaults to the server's project.");
@@ -0,0 +1,17 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { Docs } from "./docs";
3
+ export { GENERATORS } from "./tools/generate";
4
+ export type ServerOptions = {
5
+ /** Project used when a tool call gives no `cwd`. Defaults to `MEGH_PROJECT_ROOT`, else `process.cwd()`. */
6
+ projectRoot?: string;
7
+ /** Version reported to clients. */
8
+ version?: string;
9
+ /**
10
+ * Leave out the tools that write files or change the database (generators,
11
+ * build, migrate, rollback, seed). Defaults to `MEGH_MCP_READ_ONLY=1`.
12
+ */
13
+ readOnly?: boolean;
14
+ /** Docs to serve. Defaults to the bundled docs. */
15
+ docs?: Docs;
16
+ };
17
+ export declare function createServer(opts?: ServerOptions): McpServer;
package/dist/server.js ADDED
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GENERATORS = void 0;
4
+ exports.createServer = createServer;
5
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
6
+ const docs_1 = require("./docs");
7
+ const megh_1 = require("./megh");
8
+ const prompts_1 = require("./prompts");
9
+ const database_1 = require("./tools/database");
10
+ const docs_2 = require("./tools/docs");
11
+ const generate_1 = require("./tools/generate");
12
+ const project_1 = require("./tools/project");
13
+ var generate_2 = require("./tools/generate");
14
+ Object.defineProperty(exports, "GENERATORS", { enumerable: true, get: function () { return generate_2.GENERATORS; } });
15
+ function createServer(opts = {}) {
16
+ const defaultRoot = opts.projectRoot ?? process.env.MEGH_PROJECT_ROOT ?? process.cwd();
17
+ const readOnly = opts.readOnly ?? process.env.MEGH_MCP_READ_ONLY === "1";
18
+ const server = new mcp_js_1.McpServer({ name: "megh", version: opts.version ?? "0.0.0" }, {
19
+ instructions: "Tools for Megh (@meghjs/core) applications, a TypeScript web framework on Fastify. " +
20
+ "Start with megh_project_info, megh_doctor and megh_project_structure to understand the project, " +
21
+ "and megh_list_routes to see its HTTP API. Before writing Megh code, look up the API with " +
22
+ "megh_search_docs and megh_read_doc rather than guessing. " +
23
+ (readOnly
24
+ ? "This server is read-only: it cannot write files or change the database."
25
+ : "Generate code with megh_make and the megh_scaffold_* tools, the way the megh CLI does, " +
26
+ "and check it with megh_typecheck."),
27
+ });
28
+ const ctx = {
29
+ server,
30
+ project: (cwd) => (0, megh_1.resolveProject)(cwd, defaultRoot),
31
+ docs: opts.docs ?? new docs_1.Docs(),
32
+ readOnly,
33
+ };
34
+ (0, project_1.registerProjectTools)(ctx);
35
+ (0, generate_1.registerGenerateTools)(ctx);
36
+ (0, database_1.registerDatabaseTools)(ctx);
37
+ (0, docs_2.registerDocs)(ctx);
38
+ (0, prompts_1.registerPrompts)(ctx);
39
+ return server;
40
+ }
@@ -0,0 +1,11 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { Docs } from "../docs";
3
+ /** What each group of tools is given when it registers. */
4
+ export type ToolContext = {
5
+ server: McpServer;
6
+ /** Resolve a tool's `cwd` argument to a project root. */
7
+ project: (cwd?: string) => string;
8
+ docs: Docs;
9
+ /** When true, tools that write files or change the database are not registered. */
10
+ readOnly: boolean;
11
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ import type { ToolContext } from "./context";
2
+ /**
3
+ * Database tools. Reading the migration status is always available; running
4
+ * migrations, rolling back and seeding are not registered in read-only mode
5
+ * and refuse to run against a production project. `migrate:reset` and
6
+ * `migrate:refresh` are left out: they drop every table.
7
+ */
8
+ export declare function registerDatabaseTools({ server, project, readOnly }: ToolContext): void;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerDatabaseTools = registerDatabaseTools;
4
+ const zod_1 = require("zod");
5
+ const megh_1 = require("../megh");
6
+ const result_1 = require("../result");
7
+ const CONNECTS = "Connects like app.useMeghORM() does, from DATABASE_URL (or DB_*) in the environment or .env.";
8
+ /**
9
+ * Database tools. Reading the migration status is always available; running
10
+ * migrations, rolling back and seeding are not registered in read-only mode
11
+ * and refuse to run against a production project. `migrate:reset` and
12
+ * `migrate:refresh` are left out: they drop every table.
13
+ */
14
+ function registerDatabaseTools({ server, project, readOnly }) {
15
+ server.registerTool("megh_migrate_status", {
16
+ title: "Migration status",
17
+ description: `Show which database migrations have run. ${CONNECTS}`,
18
+ inputSchema: { cwd: result_1.cwdArg },
19
+ annotations: { readOnlyHint: true },
20
+ }, (0, result_1.safe)(async ({ cwd }) => (0, result_1.jsonFromCli)(await (0, megh_1.runMegh)(project(cwd), ["migrate:status", "--json"]))));
21
+ if (readOnly)
22
+ return;
23
+ /** Run a command that changes the database, unless the project runs in production. */
24
+ const changeDb = async (cwd, args) => {
25
+ const root = project(cwd);
26
+ if ((0, megh_1.isProduction)(root)) {
27
+ return (0, result_1.text)(`Refusing to run megh ${args[0]}: NODE_ENV is production for ${root}. Run it yourself if you mean to change that database.`, true);
28
+ }
29
+ return (0, result_1.fromCli)(await (0, megh_1.runMegh)(root, args));
30
+ };
31
+ server.registerTool("megh_migrate", {
32
+ title: "Run migrations",
33
+ description: `Run the pending migrations (megh migrate), optionally followed by the seeders. ${CONNECTS} Refused when NODE_ENV is production.`,
34
+ inputSchema: {
35
+ cwd: result_1.cwdArg,
36
+ seed: zod_1.z.boolean().optional().describe("Run the seeders afterwards."),
37
+ },
38
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
39
+ }, (0, result_1.safe)(({ cwd, seed }) => changeDb(cwd, ["migrate", ...(seed ? ["--seed"] : [])])));
40
+ server.registerTool("megh_migrate_rollback", {
41
+ title: "Roll back migrations",
42
+ description: `Undo the last migration, or the last \`step\` migrations (megh migrate:rollback). This can drop tables and their data. ${CONNECTS} Refused when NODE_ENV is production.`,
43
+ inputSchema: {
44
+ cwd: result_1.cwdArg,
45
+ step: zod_1.z.number().int().min(1).optional().describe("How many migrations to undo (default 1)."),
46
+ },
47
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
48
+ }, (0, result_1.safe)(({ cwd, step }) => changeDb(cwd, ["migrate:rollback", ...(step ? ["--step", String(step)] : [])])));
49
+ server.registerTool("megh_db_seed", {
50
+ title: "Seed the database",
51
+ description: `Run the seeders (megh db:seed): database.seeder.ts, else every seeder in file order, or just one. A run is one transaction. ${CONNECTS} Refused when NODE_ENV is production.`,
52
+ inputSchema: {
53
+ cwd: result_1.cwdArg,
54
+ seeder: zod_1.z.string().optional().describe("Run only this seeder, e.g. users for users.seeder.ts."),
55
+ },
56
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
57
+ }, (0, result_1.safe)(({ cwd, seeder }) => changeDb(cwd, ["db:seed", ...(seeder ? ["--seeder", seeder] : [])])));
58
+ }
@@ -0,0 +1,3 @@
1
+ import type { ToolContext } from "./context";
2
+ /** Tools and resources for the bundled Megh documentation, plus project resources. */
3
+ export declare function registerDocs({ server, project, docs }: ToolContext): void;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerDocs = registerDocs;
4
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
5
+ const zod_1 = require("zod");
6
+ const megh_1 = require("../megh");
7
+ const result_1 = require("../result");
8
+ const NO_DOCS = "The Megh docs are not bundled with this server build.";
9
+ /** Tools and resources for the bundled Megh documentation, plus project resources. */
10
+ function registerDocs({ server, project, docs }) {
11
+ server.registerTool("megh_search_docs", {
12
+ title: "Search the Megh docs",
13
+ description: "Search the Megh documentation (controllers, validation, DI, ORM, migrations, auth, queues, mail, CLI, ...) and return the best-matching pages with snippets. Read a page with megh_read_doc.",
14
+ inputSchema: {
15
+ query: zod_1.z.string().min(1).describe("What to look for, e.g. 'validate request body' or 'belongsTo relation'."),
16
+ limit: zod_1.z.number().int().min(1).max(20).optional().describe("How many pages to return (default 5)."),
17
+ },
18
+ annotations: { readOnlyHint: true },
19
+ }, (0, result_1.safe)(({ query, limit }) => {
20
+ if (!docs.available)
21
+ return (0, result_1.text)(NO_DOCS, true);
22
+ const hits = docs.search(query, limit ?? 5);
23
+ return (0, result_1.text)(hits.length ? hits : `No docs pages match "${query}". List them with megh_read_doc and no page.`);
24
+ }));
25
+ server.registerTool("megh_read_doc", {
26
+ title: "Read a Megh docs page",
27
+ description: "Read a page of the Megh documentation as markdown, by path, e.g. core-concept/controller or cli/generators. Without a page, list every page with its title and description.",
28
+ inputSchema: {
29
+ page: zod_1.z.string().optional().describe("Page path, e.g. advanced/orm. Omit to list the pages."),
30
+ },
31
+ annotations: { readOnlyHint: true },
32
+ }, (0, result_1.safe)(({ page }) => {
33
+ if (!docs.available)
34
+ return (0, result_1.text)(NO_DOCS, true);
35
+ if (!page)
36
+ return (0, result_1.text)(docs.list());
37
+ const body = docs.read(page);
38
+ return body ? (0, result_1.text)(body) : (0, result_1.text)(`No docs page "${page}". Call megh_read_doc without a page to list them.`, true);
39
+ }));
40
+ if (docs.available) {
41
+ server.registerResource("megh-docs", new mcp_js_1.ResourceTemplate("megh://docs/{+page}", {
42
+ list: () => ({
43
+ resources: docs.list().map((p) => ({
44
+ uri: `megh://docs/${p.path}`,
45
+ name: p.path,
46
+ title: p.title,
47
+ description: p.description || undefined,
48
+ mimeType: "text/markdown",
49
+ })),
50
+ }),
51
+ }), { title: "Megh docs", description: "Pages of the Megh documentation.", mimeType: "text/markdown" }, (uri, { page }) => {
52
+ const body = docs.read(String(page));
53
+ if (!body)
54
+ throw new Error(`No docs page ${uri.href}`);
55
+ return { contents: [{ uri: uri.href, mimeType: "text/markdown", text: body }] };
56
+ });
57
+ }
58
+ const json = (uri, value) => ({
59
+ contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(value, null, 2) }],
60
+ });
61
+ server.registerResource("megh-project", "megh://project/info", { title: "Project info", description: "The server's Megh project: dependencies, scripts and settings.", mimeType: "application/json" }, (uri) => json(uri, (0, megh_1.projectInfo)(project())));
62
+ server.registerResource("megh-structure", "megh://project/structure", { title: "Project structure", description: "The server's project source files, grouped by kind.", mimeType: "application/json" }, (uri) => json(uri, (0, megh_1.projectStructure)(project())));
63
+ }
@@ -0,0 +1,10 @@
1
+ import type { ToolContext } from "./context";
2
+ /** The `make:*` generators the `megh_make` tool can run. */
3
+ export declare const GENERATORS: readonly ["model", "controller", "service", "resource", "dto", "config", "middleware", "mail", "event", "listener", "queue", "worker", "task", "migration", "seeder", "factory"];
4
+ /** Values `megh scaffold:auth --strategy` accepts. */
5
+ export declare const AUTH_STRATEGIES: readonly ["jwt", "api-key", "both"];
6
+ /**
7
+ * Tools that write source files through the megh generators. Every call passes
8
+ * `--yes`: the CLI never prompts, and existing files are only replaced with `force`.
9
+ */
10
+ export declare function registerGenerateTools({ server, project, readOnly }: ToolContext): void;