@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
@@ -0,0 +1,227 @@
1
+ ---
2
+ title: FAQ and Troubleshooting
3
+ description: Answers to common questions and fixes for the problems people hit most often.
4
+ ---
5
+
6
+ # FAQ and Troubleshooting
7
+
8
+ Start with `megh doctor` when something looks wrong. It checks the Node
9
+ version, that `@meghjs/core` matches the CLI, that `reflect-metadata` is
10
+ installed and that both decorator flags are on in `tsconfig.json`.
11
+
12
+ ```bash
13
+ npx megh doctor
14
+ ```
15
+
16
+ ## Troubleshooting
17
+
18
+ ### DTOs aren't validated, or injected services are `undefined`
19
+
20
+ Megh reads TypeScript's decorator metadata (`design:paramtypes`) to find
21
+ constructor dependencies and the DTO class of a `@Body()` or `@Query()`
22
+ parameter. Without it, a `@Body()` or `@Query()` without `{ type }` stops
23
+ startup with `@Body() (parameter 0) has no type, because decorator metadata
24
+ wasn't emitted`. Constructor parameters are `undefined`, so you may also see
25
+ `TypeError: Cannot read properties of undefined` in a handler.
26
+
27
+ Turn both flags on:
28
+
29
+ ```json [tsconfig.json]
30
+ {
31
+ "compilerOptions": {
32
+ "experimentalDecorators": true,
33
+ "emitDecoratorMetadata": true
34
+ }
35
+ }
36
+ ```
37
+
38
+ Then check the compiler. `tsc`, `megh serve` and `megh build` emit the
39
+ metadata. **tsx and esbuild don't**, and SWC only does with
40
+ `jsc.transform.decoratorMetadata: true`. If you must use one of them, name
41
+ the types yourself:
42
+
43
+ ```ts
44
+ import { ApiController, Post, Body, inject } from '@meghjs/core';
45
+
46
+ @ApiController('/users')
47
+ export class UserController {
48
+ private readonly users = inject(UserService); // instead of a constructor parameter
49
+
50
+ @Post('/')
51
+ create(@Body({ type: CreateUserDto }) dto: CreateUserDto) {
52
+ return this.users.create(dto);
53
+ }
54
+ }
55
+ ```
56
+
57
+ ### Do I need `import 'reflect-metadata'`?
58
+
59
+ Usually not. `@meghjs/core` imports it on load. Add it as the first line of
60
+ your entry file only if classes decorated by other libraries (a DTO that only
61
+ uses `class-validator`, say) can be loaded before anything imports
62
+ `@meghjs/core`. TypeScript drops the metadata silently when
63
+ `Reflect.metadata` doesn't exist yet.
64
+
65
+ ```ts [src/serve.ts]
66
+ import 'reflect-metadata';
67
+ import app from './app';
68
+ ```
69
+
70
+ ### ESM or CommonJS?
71
+
72
+ `@meghjs/core` ships a single CommonJS build. ESM projects can import it, but
73
+ the CLI (`serve`, `build`, `start`) and the scaffold assume a CommonJS app:
74
+ `"module": "CommonJS"` in `tsconfig.json` and no `"type": "module"` in
75
+ `package.json`. If you add `"type": "module"`, Node loads the compiled
76
+ CommonJS files as ES modules and stops with
77
+ `ReferenceError: exports is not defined in ES module scope`. Remove it, or
78
+ compile and run the app yourself as real ESM.
79
+
80
+ ### `Cannot access 'User' before initialization` between models
81
+
82
+ This happens only in ES module builds, when two models import each other and
83
+ a relation field is typed with the bare model:
84
+
85
+ ```ts
86
+ @BelongsTo(() => User)
87
+ author?: User; // breaks in ESM when User imports Post
88
+ author?: User | null; // fine
89
+ author?: BelongsTo<User>; // fine
90
+ ```
91
+
92
+ Keep `| null` on `@HasOne` and `@BelongsTo` fields, or use the `HasOne<…>` /
93
+ `BelongsTo<…>` types. CommonJS builds are not affected. See
94
+ [Relations](/advanced/orm/relations).
95
+
96
+ ### `[Megh] … is not installed`
97
+
98
+ Integrations are optional peer dependencies, loaded when the app sets up the
99
+ feature (for most, when you call its `use*` method). The error names the
100
+ command to run:
101
+
102
+ ```text
103
+ [Megh] fastify-socket.io is not installed.
104
+ Run: npm install fastify-socket.io socket.io
105
+ ```
106
+
107
+ The same applies to `@fastify/cors`, `@fastify/multipart`, `@fastify/static`,
108
+ `@fastify/swagger`, `@fastify/swagger-ui` and
109
+ `@scalar/fastify-api-reference`. Database drivers fail with
110
+ `The postgres connection needs "pg". Install it: npm install pg`.
111
+
112
+ If it works locally but fails in production, the package is probably in
113
+ `devDependencies` and was left out by `npm ci --omit=dev`. Move it to
114
+ `dependencies`, or only call that `use*` method in development.
115
+
116
+ ### Every `@Authorized` route answers 403
117
+
118
+ No authorization handler is registered. Megh denies those routes instead of
119
+ serving them, and logs this at startup:
120
+
121
+ ```text
122
+ GET /users uses @Authorized but no authorization handler is registered;
123
+ every request will be denied (403). Call app.useAuthorization(YourAuthorization).
124
+ ```
125
+
126
+ Register one with `app.useAuthorization(AppAuthorization)`. If you have one,
127
+ check that it doesn't return `false` (that is a 403 too) and that
128
+ `useAuthentication` is set, so `request.user` is filled in. See
129
+ [Authentication](/core-concept/authentication).
130
+
131
+ ### Auto-discovered controllers aren't found
132
+
133
+ `useControllers({ auto: true })` scans every `controllers/` folder under
134
+ `src/` (`src/controllers/`, `src/users/controllers/`). When TypeScript runs
135
+ directly (ts-node, tsx, `node --experimental-strip-types src/serve.ts`) it
136
+ loads the `.ts` files from `src`. Otherwise it loads the compiled `.js`
137
+ files: it reads `rootDir` and `outDir` from `tsconfig.build.json` or
138
+ `tsconfig.json` (defaults `src` and `dist`) and also tries the nested
139
+ `dist/src/controllers` when `rootDir` isn't set. Paths are relative to the
140
+ current working directory. Routes go missing when:
141
+
142
+ - **The app wasn't built**, so the compiled folder doesn't exist yet.
143
+ - **The tsconfig isn't in the working directory**, or `outDir` comes from a
144
+ package `extends` (only relative `extends` are followed). Pass the
145
+ compiled folder: `useControllers({ auto: true, path: 'build/controllers' })`.
146
+ - **The app starts from another directory.** Start it from the project root.
147
+
148
+ When the folder doesn't exist, Megh logs `Could not auto-register
149
+ controllers` with the folder it tried. A file in it that fails to import
150
+ stops startup with the file name and the error. Passing a list,
151
+ `useControllers([UserController, ...])`, avoids all of this.
152
+
153
+ ### `EADDRINUSE: address already in use`
154
+
155
+ Another process is listening on the port, often an old dev server. Stop it,
156
+ or pick another port:
157
+
158
+ ```bash
159
+ PORT=4001 npm run start:dev
160
+ ```
161
+
162
+ Find the process with `lsof -i :4000` (macOS, Linux) or
163
+ `netstat -ano | findstr :4000` (Windows). `app.run()` uses `PORT`, else
164
+ `4000`, unless you pass a port.
165
+
166
+ ### `.env` isn't loaded
167
+
168
+ - Megh loads `.env` from the **current working directory** when
169
+ `@meghjs/core` is first imported. Start the app from the project root.
170
+ - Variables already in the environment win over `.env`.
171
+ - `MEGH_DOTENV=false` turns loading off.
172
+ - Code that reads `process.env` before importing `@meghjs/core` runs before
173
+ `.env` is loaded. Read config through `Environment` or after the import.
174
+ - Only `.env` is read. Megh doesn't load `.env.local` or `.env.production`.
175
+
176
+ See [Configuration](/core-concept/configuration).
177
+
178
+ ### Detailed errors show up in production
179
+
180
+ `NODE_ENV` is `development` there, often from a `.env` file copied with the
181
+ app. Set `NODE_ENV=production` in the real environment and don't ship `.env`.
182
+ See [Deployment](/production/deployment#environment).
183
+
184
+ ### Scheduled jobs run more than once
185
+
186
+ Each replica runs the scheduler. Start it in one process only. See
187
+ [Deployment](/production/deployment#scheduled-tasks-and-replicas).
188
+
189
+ ## FAQ
190
+
191
+ ### Is Megh production ready?
192
+
193
+ Megh runs on Fastify and has the pieces production needs: graceful shutdown,
194
+ health checks, structured logs and safe error responses. It is still `0.x`,
195
+ so a minor release can contain breaking changes, each with an upgrade guide.
196
+ Pin the version and read the guide before upgrading. See
197
+ [Deployment](/production/deployment) and
198
+ [Security Hardening](/production/security).
199
+
200
+ ### How does Megh compare to NestJS?
201
+
202
+ Both use decorators, dependency injection and controllers. Megh runs on
203
+ Fastify only and has no module system: classes marked `@Injectable` or
204
+ `@AppService` are available everywhere, with no provider arrays to keep in
205
+ sync. It ships its own ORM, migrations, scaffolding and CLI generators.
206
+ NestJS supports Express and Fastify, has a module system for large codebases
207
+ and a much larger ecosystem and community.
208
+
209
+ ### Can I use Fastify plugins?
210
+
211
+ Yes. `app.app` is the Fastify instance:
212
+
213
+ ```ts
214
+ import compress from '@fastify/compress';
215
+
216
+ app.onInit(async () => {
217
+ await app.app.register(compress);
218
+ });
219
+ ```
220
+
221
+ Some plugins, such as `@fastify/compress`, attach themselves to each route
222
+ as it is added. Megh adds routes during `run()`, after the `onInit` hooks, so
223
+ registering and awaiting the plugin in `onInit` makes sure it sees every
224
+ controller and inline route. Security headers and rate limits are built in:
225
+ see [Security Hardening](/production/security#add-security-headers).
226
+ To package your own features as `use*` methods, write a
227
+ [Megh plugin](/advanced/plugins).
@@ -0,0 +1,105 @@
1
+ ---
2
+ title: Versioning Policy
3
+ description: How Megh versions its packages, what counts as a breaking change, and how to upgrade.
4
+ ---
5
+
6
+ # Versioning Policy
7
+
8
+ Megh follows [semantic versioning](https://semver.org): `MAJOR.MINOR.PATCH`.
9
+
10
+ ## One version for every package
11
+
12
+ `@meghjs/core`, `@meghjs/cli` and `@meghjs/mcp` are released together and
13
+ always share the same version number, even when only one of them changed. Use
14
+ matching versions:
15
+
16
+ ```json [package.json]
17
+ {
18
+ "dependencies": { "@meghjs/core": "0.7.0" },
19
+ "devDependencies": { "@meghjs/cli": "0.7.0" }
20
+ }
21
+ ```
22
+
23
+ ## Before 1.0
24
+
25
+ Megh is in `0.x`. Until 1.0:
26
+
27
+ | Release | Can contain |
28
+ |---------|-------------|
29
+ | Minor (`0.6.x` → `0.7.0`) | Breaking changes, plus anything else |
30
+ | Patch (`0.6.0` → `0.6.1`) | Bug fixes and new features. No breaking changes |
31
+
32
+ New features ship in patch releases, so a minor release before 1.0 means
33
+ something can break: read its upgrade guide first. 0.7.0 is the last minor
34
+ before 1.0; see [Upgrading to 0.7](/getting-started/upgrading-0.7).
35
+
36
+ Pin an exact version or use a tilde range (`~0.7.0`) so `npm install` never
37
+ picks up a new minor on its own. A caret range (`^0.7.0`) on a `0.x` version
38
+ already behaves like a tilde range.
39
+
40
+ Fixes go into the latest release only.
41
+
42
+ ## From 1.0
43
+
44
+ | Release | Can contain |
45
+ |---------|-------------|
46
+ | Major (`1.x` → `2.0`) | Breaking changes |
47
+ | Minor (`1.2` → `1.3`) | New features and deprecations |
48
+ | Patch (`1.2.0` → `1.2.1`) | Bug fixes |
49
+
50
+ An API is deprecated in a minor release before it's removed in a major one.
51
+ Deprecated APIs are marked `@deprecated` in their types, so your editor shows
52
+ them struck through, and listed in the release notes.
53
+
54
+ ## What counts as the public API
55
+
56
+ The public API is:
57
+
58
+ - everything exported from `@meghjs/core` (`import { … } from '@meghjs/core'`)
59
+ - the `megh` CLI commands and their options
60
+ - behaviour described in these docs, such as response shapes, status codes
61
+ and the order of the request pipeline
62
+
63
+ These are **not** part of the public API and can change in any release:
64
+
65
+ - options under `experimental`, such as `experimental.compiledValidation`
66
+ - members marked `@deprecated` or described as internal
67
+ - the exports listed under [Other exports](/reference/api#other-exports) in
68
+ the API reference. They're exported for Megh's own packages and may be
69
+ hidden or removed before 1.0
70
+ - deep imports such as `@meghjs/core/dist/...`. The package's `exports` map
71
+ blocks them anyway.
72
+ - the exact text of log and error messages
73
+
74
+ ## Breaking changes
75
+
76
+ A change is breaking when a working app needs a code change to keep working
77
+ after the upgrade. For example:
78
+
79
+ - removing or renaming an export, method, decorator or option
80
+ - changing a default value, response shape or status code
81
+ - raising the minimum Node.js version (today `>=22`)
82
+ - raising the major version of a peer dependency, such as `@fastify/multipart`
83
+
84
+ Fixing a bug is not breaking, even when an app relied on the bug. If a fix is
85
+ likely to affect many apps, the release notes call it out.
86
+
87
+ ## How changes are announced
88
+
89
+ Each release has:
90
+
91
+ - **A changelog**, generated from the commit messages. Breaking changes are
92
+ listed under a `BREAKING CHANGES` heading.
93
+ See [packages/core/CHANGELOG.md](https://github.com/meghjs/megh/blob/main/packages/core/CHANGELOG.md).
94
+ - **An upgrade guide** for any release with breaking changes, under
95
+ *Upgrade Guides* in the sidebar, with before-and-after code.
96
+ - **[Upcoming changes](/getting-started/upgrading-next)**, which lists what has
97
+ landed on `main` since the last release. Read it to prepare ahead of time.
98
+
99
+ ## Upgrading
100
+
101
+ 1. Read the upgrade guide for each release between your version and the new
102
+ one, oldest first.
103
+ 2. Update `@meghjs/core` and `@meghjs/cli` to the same version.
104
+ 3. Run your type checker. Most removals show up as type errors.
105
+ 4. Run your tests.
package/dist/docs.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ export type DocPage = {
2
+ /** Path without `.md`, e.g. `core-concept/controller`. */
3
+ path: string;
4
+ title: string;
5
+ description: string;
6
+ };
7
+ export type DocHit = DocPage & {
8
+ score: number;
9
+ snippets: string[];
10
+ };
11
+ /**
12
+ * Where the docs are: `dist/docs` in the published package (copied at build
13
+ * time), else the monorepo's `docs/content` when running from source.
14
+ */
15
+ export declare function findDocsDir(): string | null;
16
+ export declare class Docs {
17
+ readonly dir: string | null;
18
+ private pages;
19
+ constructor(dir?: string | null);
20
+ get available(): boolean;
21
+ private index;
22
+ list(): DocPage[];
23
+ /** A page's markdown, by path with or without `.md`. */
24
+ read(page: string): string | null;
25
+ /**
26
+ * Rank pages by the query's words: a match in the title counts most, then
27
+ * headings, description and body. Returns short snippets around body matches.
28
+ */
29
+ search(query: string, limit?: number): DocHit[];
30
+ }
package/dist/docs.js ADDED
@@ -0,0 +1,126 @@
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.Docs = void 0;
7
+ exports.findDocsDir = findDocsDir;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ /**
11
+ * Where the docs are: `dist/docs` in the published package (copied at build
12
+ * time), else the monorepo's `docs/content` when running from source.
13
+ */
14
+ function findDocsDir() {
15
+ const candidates = [
16
+ process.env.MEGH_DOCS_DIR,
17
+ path_1.default.join(__dirname, "docs"),
18
+ path_1.default.join(__dirname, "..", "dist", "docs"),
19
+ path_1.default.join(__dirname, "..", "..", "..", "docs", "content"),
20
+ ];
21
+ return candidates.find((dir) => dir && fs_1.default.existsSync(path_1.default.join(dir, "index.md"))) ?? null;
22
+ }
23
+ /** Split `---` frontmatter (only flat `key: value` lines) from the body. */
24
+ function frontmatter(source) {
25
+ const m = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
26
+ if (!m)
27
+ return { meta: {}, body: source };
28
+ const meta = {};
29
+ for (const line of m[1].split(/\r?\n/)) {
30
+ const kv = line.match(/^(\w+):\s*(.*)$/);
31
+ if (kv)
32
+ meta[kv[1]] = kv[2].trim().replace(/^["']|["']$/g, "");
33
+ }
34
+ return { meta, body: source.slice(m[0].length) };
35
+ }
36
+ class Docs {
37
+ dir;
38
+ pages = null;
39
+ constructor(dir = findDocsDir()) {
40
+ this.dir = dir;
41
+ }
42
+ get available() {
43
+ return this.dir !== null;
44
+ }
45
+ index() {
46
+ if (this.pages)
47
+ return this.pages;
48
+ if (!this.dir)
49
+ return (this.pages = []);
50
+ const dir = this.dir;
51
+ const files = fs_1.default
52
+ .readdirSync(dir, { recursive: true, withFileTypes: true })
53
+ .filter((e) => e.isFile() && e.name.endsWith(".md"))
54
+ .map((e) => path_1.default.join(e.parentPath ?? e.path, e.name));
55
+ this.pages = files
56
+ .map((file) => {
57
+ const { meta, body } = frontmatter(fs_1.default.readFileSync(file, "utf8"));
58
+ const rel = path_1.default.relative(dir, file).split(path_1.default.sep).join("/").replace(/\.md$/, "");
59
+ const headings = [...body.matchAll(/^#{1,4}\s+(.+)$/gm)].map((h) => h[1].trim());
60
+ return {
61
+ path: rel,
62
+ title: meta.title || headings[0] || rel,
63
+ description: meta.description ?? "",
64
+ headings,
65
+ body,
66
+ };
67
+ })
68
+ .sort((a, b) => a.path.localeCompare(b.path));
69
+ return this.pages;
70
+ }
71
+ list() {
72
+ return this.index().map(({ path, title, description }) => ({ path, title, description }));
73
+ }
74
+ /** A page's markdown, by path with or without `.md`. */
75
+ read(page) {
76
+ const wanted = page.replace(/^\/+/, "").replace(/\.md$/, "").replace(/\/$/, "") || "index";
77
+ const hit = this.index().find((p) => p.path === wanted || p.path === `${wanted}/index`);
78
+ return hit ? `# ${hit.path}\n\n${hit.body.trim()}\n` : null;
79
+ }
80
+ /**
81
+ * Rank pages by the query's words: a match in the title counts most, then
82
+ * headings, description and body. Returns short snippets around body matches.
83
+ */
84
+ search(query, limit = 5) {
85
+ const terms = query.toLowerCase().split(/[^a-z0-9@:_.-]+/).filter((t) => t.length > 1);
86
+ if (!terms.length)
87
+ return [];
88
+ const hits = [];
89
+ for (const page of this.index()) {
90
+ const title = page.title.toLowerCase();
91
+ const headings = page.headings.join("\n").toLowerCase();
92
+ const description = page.description.toLowerCase();
93
+ const body = page.body.toLowerCase();
94
+ let score = 0;
95
+ let matched = 0;
96
+ for (const t of terms) {
97
+ const inBody = body.split(t).length - 1;
98
+ const s = (title.includes(t) ? 10 : 0) +
99
+ (headings.includes(t) ? 5 : 0) +
100
+ (description.includes(t) ? 3 : 0) +
101
+ Math.min(inBody, 10);
102
+ if (s > 0)
103
+ matched++;
104
+ score += s;
105
+ }
106
+ if (!score)
107
+ continue;
108
+ score *= matched / terms.length; // pages matching every word rank first
109
+ hits.push({ path: page.path, title: page.title, description: page.description, score, snippets: snippets(page.body, terms) });
110
+ }
111
+ return hits.sort((a, b) => b.score - a.score).slice(0, limit);
112
+ }
113
+ }
114
+ exports.Docs = Docs;
115
+ function snippets(body, terms, max = 3) {
116
+ const lines = body.split(/\r?\n/);
117
+ const out = [];
118
+ for (let i = 0; i < lines.length && out.length < max; i++) {
119
+ const line = lines[i].toLowerCase();
120
+ if (!line.trim() || !terms.some((t) => line.includes(t)))
121
+ continue;
122
+ out.push(lines.slice(Math.max(0, i - 1), i + 2).join("\n").trim());
123
+ i += 2;
124
+ }
125
+ return out;
126
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Library entry for `@meghjs/mcp`. Importing it has no side effects; the
3
+ * stdio executable lives in `bin.ts`.
4
+ */
5
+ export { createServer, GENERATORS } from "./server";
6
+ export type { ServerOptions } from "./server";
7
+ export { Docs, findDocsDir } from "./docs";
8
+ export type { DocPage, DocHit } from "./docs";
9
+ export { runMegh, runNode, resolveProject, projectInfo, projectStructure, isProduction, cliBin, tscBin } from "./megh";
10
+ export type { CliResult } from "./megh";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tscBin = exports.cliBin = exports.isProduction = exports.projectStructure = exports.projectInfo = exports.resolveProject = exports.runNode = exports.runMegh = exports.findDocsDir = exports.Docs = exports.GENERATORS = exports.createServer = void 0;
4
+ /**
5
+ * Library entry for `@meghjs/mcp`. Importing it has no side effects; the
6
+ * stdio executable lives in `bin.ts`.
7
+ */
8
+ var server_1 = require("./server");
9
+ Object.defineProperty(exports, "createServer", { enumerable: true, get: function () { return server_1.createServer; } });
10
+ Object.defineProperty(exports, "GENERATORS", { enumerable: true, get: function () { return server_1.GENERATORS; } });
11
+ var docs_1 = require("./docs");
12
+ Object.defineProperty(exports, "Docs", { enumerable: true, get: function () { return docs_1.Docs; } });
13
+ Object.defineProperty(exports, "findDocsDir", { enumerable: true, get: function () { return docs_1.findDocsDir; } });
14
+ var megh_1 = require("./megh");
15
+ Object.defineProperty(exports, "runMegh", { enumerable: true, get: function () { return megh_1.runMegh; } });
16
+ Object.defineProperty(exports, "runNode", { enumerable: true, get: function () { return megh_1.runNode; } });
17
+ Object.defineProperty(exports, "resolveProject", { enumerable: true, get: function () { return megh_1.resolveProject; } });
18
+ Object.defineProperty(exports, "projectInfo", { enumerable: true, get: function () { return megh_1.projectInfo; } });
19
+ Object.defineProperty(exports, "projectStructure", { enumerable: true, get: function () { return megh_1.projectStructure; } });
20
+ Object.defineProperty(exports, "isProduction", { enumerable: true, get: function () { return megh_1.isProduction; } });
21
+ Object.defineProperty(exports, "cliBin", { enumerable: true, get: function () { return megh_1.cliBin; } });
22
+ Object.defineProperty(exports, "tscBin", { enumerable: true, get: function () { return megh_1.tscBin; } });
package/dist/megh.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ export type CliResult = {
2
+ exitCode: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ };
6
+ /**
7
+ * Resolve the project a tool works on: the given directory, else the server's
8
+ * default (`MEGH_PROJECT_ROOT` or the directory it was started in). Walks up
9
+ * to the nearest `package.json`, like the CLI does.
10
+ */
11
+ export declare function resolveProject(cwd: string | undefined, fallback: string): string;
12
+ /**
13
+ * The `megh` executable to run. Prefers the CLI installed in the project, so
14
+ * its version matches the project's `@meghjs/core`, and falls back to the one
15
+ * this package depends on.
16
+ */
17
+ export declare function cliBin(root: string): string;
18
+ /** The project's TypeScript compiler (`typescript/bin/tsc`). */
19
+ export declare function tscBin(root: string): string;
20
+ /**
21
+ * Run a Node.js script in `root` and capture its output. It runs in its own
22
+ * process: its console output must not reach the server's stdout, which
23
+ * carries the MCP protocol. stdin is closed so a prompt cannot hang the call.
24
+ */
25
+ export declare function runNode(root: string, script: string, args: string[]): Promise<CliResult>;
26
+ /** Run `megh <args>` in `root`. */
27
+ export declare function runMegh(root: string, args: string[]): Promise<CliResult>;
28
+ /** Parse JSON a command printed with `--json`, ignoring any lines logged before it. */
29
+ export declare function parseJsonOutput(stdout: string): unknown;
30
+ /**
31
+ * Whether the project runs with `NODE_ENV=production`, from the server's
32
+ * environment or the project's `.env` (which the CLI also loads).
33
+ */
34
+ export declare function isProduction(root: string): boolean;
35
+ export declare function readPackageJson(root: string): Record<string, any>;
36
+ /** The `@meghjs/*` packages a project depends on and the `megh` settings in its package.json. */
37
+ export declare function projectInfo(root: string): {
38
+ root: string;
39
+ name: any;
40
+ version: any;
41
+ isMeghProject: boolean;
42
+ meghDependencies: {
43
+ [k: string]: string;
44
+ };
45
+ installedVersions: Record<string, string | null>;
46
+ scripts: any;
47
+ meghConfig: any;
48
+ hasEnvFile: boolean;
49
+ production: boolean;
50
+ };
51
+ /** The project's source files grouped by what they are (controllers, models, ...). */
52
+ export declare function projectStructure(root: string): {
53
+ root: string;
54
+ entry: string | null;
55
+ counts: {
56
+ [k: string]: number;
57
+ };
58
+ files: Record<string, string[]>;
59
+ };