@mapomodule/mcp 0.0.0-stage → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +509 -2
  2. package/bin/mapo-mcp.mjs +3 -0
  3. package/dist/build.d.mts +18 -0
  4. package/dist/build.d.ts +18 -0
  5. package/dist/build.mjs +351 -0
  6. package/dist/cli.d.mts +7 -0
  7. package/dist/cli.d.ts +7 -0
  8. package/dist/cli.mjs +274 -0
  9. package/dist/index.d.mts +68 -0
  10. package/dist/index.d.ts +68 -0
  11. package/dist/index.mjs +1 -0
  12. package/dist/knowledge/api.json +1 -0
  13. package/dist/knowledge/docs.json +1 -0
  14. package/dist/module.d.mts +16 -0
  15. package/dist/module.d.ts +16 -0
  16. package/dist/module.json +9 -0
  17. package/dist/module.mjs +124 -0
  18. package/dist/runtime/core/doctor.d.ts +0 -0
  19. package/dist/runtime/core/doctor.js +128 -0
  20. package/dist/runtime/core/endpoint.d.ts +0 -0
  21. package/dist/runtime/core/endpoint.js +8 -0
  22. package/dist/runtime/core/indexer.d.ts +0 -0
  23. package/dist/runtime/core/indexer.js +194 -0
  24. package/dist/runtime/core/instructions.d.ts +0 -0
  25. package/dist/runtime/core/instructions.js +10 -0
  26. package/dist/runtime/core/knowledge.d.ts +0 -0
  27. package/dist/runtime/core/knowledge.js +76 -0
  28. package/dist/runtime/core/openapi.d.ts +0 -0
  29. package/dist/runtime/core/openapi.js +229 -0
  30. package/dist/runtime/core/overview.d.ts +0 -0
  31. package/dist/runtime/core/overview.js +15 -0
  32. package/dist/runtime/core/prompts.d.ts +0 -0
  33. package/dist/runtime/core/prompts.js +108 -0
  34. package/dist/runtime/core/recipes.d.ts +0 -0
  35. package/dist/runtime/core/recipes.js +496 -0
  36. package/dist/runtime/core/resources.d.ts +0 -0
  37. package/dist/runtime/core/resources.js +92 -0
  38. package/dist/runtime/core/scaffold/fields.d.ts +0 -0
  39. package/dist/runtime/core/scaffold/fields.js +64 -0
  40. package/dist/runtime/core/scaffold/index.d.ts +0 -0
  41. package/dist/runtime/core/scaffold/index.js +74 -0
  42. package/dist/runtime/core/scaffold/templates.d.ts +0 -0
  43. package/dist/runtime/core/scaffold/templates.js +349 -0
  44. package/dist/runtime/core/schema-source.d.ts +0 -0
  45. package/dist/runtime/core/schema-source.js +70 -0
  46. package/dist/runtime/core/search.d.ts +0 -0
  47. package/dist/runtime/core/search.js +173 -0
  48. package/dist/runtime/core/tokenize.d.ts +0 -0
  49. package/dist/runtime/core/tokenize.js +96 -0
  50. package/dist/runtime/core/tool-spec.d.ts +0 -0
  51. package/dist/runtime/core/tool-spec.js +3 -0
  52. package/dist/runtime/core/tools/api.d.ts +0 -0
  53. package/dist/runtime/core/tools/api.js +192 -0
  54. package/dist/runtime/core/tools/app.d.ts +0 -0
  55. package/dist/runtime/core/tools/app.js +141 -0
  56. package/dist/runtime/core/tools/backend.d.ts +0 -0
  57. package/dist/runtime/core/tools/backend.js +143 -0
  58. package/dist/runtime/core/tools/docs.d.ts +0 -0
  59. package/dist/runtime/core/tools/docs.js +154 -0
  60. package/dist/runtime/core/tools/scaffold.d.ts +0 -0
  61. package/dist/runtime/core/tools/scaffold.js +127 -0
  62. package/dist/runtime/core/types.d.ts +0 -0
  63. package/dist/runtime/core/types.js +0 -0
  64. package/dist/runtime/core/write.d.ts +0 -0
  65. package/dist/runtime/core/write.js +53 -0
  66. package/dist/runtime/mcp/handlers/mapo/index.js +7 -0
  67. package/dist/runtime/mcp/handlers/mapo/prompts/crud-page.js +3 -0
  68. package/dist/runtime/mcp/handlers/mapo/prompts/custom-field.js +3 -0
  69. package/dist/runtime/mcp/handlers/mapo/prompts/debug-form.js +3 -0
  70. package/dist/runtime/mcp/handlers/mapo/prompts/migrate-v1.js +3 -0
  71. package/dist/runtime/mcp/handlers/mapo/prompts/theme.js +3 -0
  72. package/dist/runtime/mcp/handlers/mapo/resources/app-manifest.js +19 -0
  73. package/dist/runtime/mcp/handlers/mapo/resources/docs.js +34 -0
  74. package/dist/runtime/mcp/handlers/mapo/resources/fields.js +34 -0
  75. package/dist/runtime/mcp/handlers/mapo/resources/knowledge-index.js +22 -0
  76. package/dist/runtime/mcp/handlers/mapo/resources/overview.js +20 -0
  77. package/dist/runtime/mcp/handlers/mapo/tools/backend-schema.js +3 -0
  78. package/dist/runtime/mcp/handlers/mapo/tools/component-api.js +3 -0
  79. package/dist/runtime/mcp/handlers/mapo/tools/composable-api.js +3 -0
  80. package/dist/runtime/mcp/handlers/mapo/tools/doctor.js +3 -0
  81. package/dist/runtime/mcp/handlers/mapo/tools/get-doc.js +3 -0
  82. package/dist/runtime/mcp/handlers/mapo/tools/inspect-app.js +3 -0
  83. package/dist/runtime/mcp/handlers/mapo/tools/list-field-types.js +3 -0
  84. package/dist/runtime/mcp/handlers/mapo/tools/list-recipes.js +3 -0
  85. package/dist/runtime/mcp/handlers/mapo/tools/scaffold.js +3 -0
  86. package/dist/runtime/mcp/handlers/mapo/tools/search-docs.js +3 -0
  87. package/dist/runtime/nitro/context.d.ts +0 -0
  88. package/dist/runtime/nitro/context.js +21 -0
  89. package/dist/runtime/nitro/to-mcp-prompt.d.ts +0 -0
  90. package/dist/runtime/nitro/to-mcp-prompt.js +23 -0
  91. package/dist/runtime/nitro/to-mcp-tool.d.ts +0 -0
  92. package/dist/runtime/nitro/to-mcp-tool.js +28 -0
  93. package/dist/runtime/types/virtual-modules.d.ts +6 -0
  94. package/dist/types.d.mts +9 -0
  95. package/package.json +73 -4
  96. package/src/__tests__/cli.test.ts +137 -0
  97. package/src/__tests__/doctor.test.ts +145 -0
  98. package/src/__tests__/endpoint.test.ts +31 -0
  99. package/src/__tests__/fixtures/drf-schema.json +142 -0
  100. package/src/__tests__/fixtures.ts +198 -0
  101. package/src/__tests__/indexer.test.ts +114 -0
  102. package/src/__tests__/knowledge.test.ts +225 -0
  103. package/src/__tests__/openapi.test.ts +256 -0
  104. package/src/__tests__/overview.test.ts +105 -0
  105. package/src/__tests__/recipes.test.ts +55 -0
  106. package/src/__tests__/resources.test.ts +69 -0
  107. package/src/__tests__/scaffold.test.ts +153 -0
  108. package/src/__tests__/search.test.ts +105 -0
  109. package/src/__tests__/tools.test.ts +226 -0
  110. package/src/__tests__/write.test.ts +134 -0
  111. package/src/build/extract-components.ts +135 -0
  112. package/src/build/extract-composables.ts +125 -0
  113. package/src/build/extract-fields.ts +250 -0
  114. package/src/build/index.ts +103 -0
  115. package/src/cli.ts +375 -0
  116. package/src/index.ts +65 -0
  117. package/src/module.ts +213 -0
  118. package/src/runtime/core/doctor.ts +204 -0
  119. package/src/runtime/core/endpoint.ts +27 -0
  120. package/src/runtime/core/indexer.ts +285 -0
  121. package/src/runtime/core/instructions.ts +18 -0
  122. package/src/runtime/core/knowledge.ts +121 -0
  123. package/src/runtime/core/openapi.ts +417 -0
  124. package/src/runtime/core/overview.ts +44 -0
  125. package/src/runtime/core/prompts.ts +150 -0
  126. package/src/runtime/core/recipes.ts +574 -0
  127. package/src/runtime/core/resources.ts +150 -0
  128. package/src/runtime/core/scaffold/fields.ts +127 -0
  129. package/src/runtime/core/scaffold/index.ts +120 -0
  130. package/src/runtime/core/scaffold/templates.ts +394 -0
  131. package/src/runtime/core/schema-source.ts +123 -0
  132. package/src/runtime/core/search.ts +282 -0
  133. package/src/runtime/core/tokenize.ts +146 -0
  134. package/src/runtime/core/tool-spec.ts +74 -0
  135. package/src/runtime/core/tools/api.ts +300 -0
  136. package/src/runtime/core/tools/app.ts +201 -0
  137. package/src/runtime/core/tools/backend.ts +197 -0
  138. package/src/runtime/core/tools/docs.ts +218 -0
  139. package/src/runtime/core/tools/scaffold.ts +176 -0
  140. package/src/runtime/core/types.ts +133 -0
  141. package/src/runtime/core/write.ts +119 -0
  142. package/src/runtime/mcp/handlers/mapo/index.ts +16 -0
  143. package/src/runtime/mcp/handlers/mapo/prompts/crud-page.ts +4 -0
  144. package/src/runtime/mcp/handlers/mapo/prompts/custom-field.ts +4 -0
  145. package/src/runtime/mcp/handlers/mapo/prompts/debug-form.ts +4 -0
  146. package/src/runtime/mcp/handlers/mapo/prompts/migrate-v1.ts +4 -0
  147. package/src/runtime/mcp/handlers/mapo/prompts/theme.ts +4 -0
  148. package/src/runtime/mcp/handlers/mapo/resources/app-manifest.ts +28 -0
  149. package/src/runtime/mcp/handlers/mapo/resources/docs.ts +41 -0
  150. package/src/runtime/mcp/handlers/mapo/resources/fields.ts +37 -0
  151. package/src/runtime/mcp/handlers/mapo/resources/knowledge-index.ts +24 -0
  152. package/src/runtime/mcp/handlers/mapo/resources/overview.ts +22 -0
  153. package/src/runtime/mcp/handlers/mapo/tools/backend-schema.ts +4 -0
  154. package/src/runtime/mcp/handlers/mapo/tools/component-api.ts +4 -0
  155. package/src/runtime/mcp/handlers/mapo/tools/composable-api.ts +4 -0
  156. package/src/runtime/mcp/handlers/mapo/tools/doctor.ts +4 -0
  157. package/src/runtime/mcp/handlers/mapo/tools/get-doc.ts +4 -0
  158. package/src/runtime/mcp/handlers/mapo/tools/inspect-app.ts +4 -0
  159. package/src/runtime/mcp/handlers/mapo/tools/list-field-types.ts +4 -0
  160. package/src/runtime/mcp/handlers/mapo/tools/list-recipes.ts +4 -0
  161. package/src/runtime/mcp/handlers/mapo/tools/scaffold.ts +4 -0
  162. package/src/runtime/mcp/handlers/mapo/tools/search-docs.ts +4 -0
  163. package/src/runtime/nitro/context.ts +41 -0
  164. package/src/runtime/nitro/to-mcp-prompt.ts +30 -0
  165. package/src/runtime/nitro/to-mcp-tool.ts +35 -0
  166. package/src/runtime/types/virtual-modules.d.ts +6 -0
package/src/cli.ts ADDED
@@ -0,0 +1,375 @@
1
+ /**
2
+ * `mapo-mcp` — standalone MCP server over stdio.
3
+ *
4
+ * Exposes the same tool specs as the Nuxt module, so an IDE stays useful even
5
+ * when the dev server is down. The tools that need the running app are
6
+ * forwarded to it when it is reachable (see `createAppProxy`).
7
+ *
8
+ * stdout is reserved for the MCP protocol: every log goes to stderr.
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
12
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
13
+ import {
14
+ McpServer,
15
+ ResourceTemplate,
16
+ } from "@modelcontextprotocol/sdk/server/mcp.js";
17
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
+ import { defineCommand, runMain } from "citty";
19
+ import {
20
+ DOCS_URI_PREFIX,
21
+ FIELD_URI_PREFIX,
22
+ INDEX_URI,
23
+ OVERVIEW_URI,
24
+ docResourceList,
25
+ fieldResourceList,
26
+ renderDocResource,
27
+ renderFieldResource,
28
+ renderKnowledgeIndex,
29
+ } from "./runtime/core/resources.js";
30
+ import { mcpEndpointUrl } from "./runtime/core/endpoint.js";
31
+ import { MAPO_INSTRUCTIONS } from "./runtime/core/instructions.js";
32
+ import { renderOverview } from "./runtime/core/overview.js";
33
+ import { apiTools } from "./runtime/core/tools/api.js";
34
+ import { appTools } from "./runtime/core/tools/app.js";
35
+ import { docsTools } from "./runtime/core/tools/docs.js";
36
+ import { scaffoldTools } from "./runtime/core/tools/scaffold.js";
37
+ import { backendTools } from "./runtime/core/tools/backend.js";
38
+ import { PROMPTS } from "./runtime/core/prompts.js";
39
+ import {
40
+ loadApiKnowledge,
41
+ loadDocsKnowledge,
42
+ resolveKnowledgeDir,
43
+ } from "./runtime/core/knowledge.js";
44
+ import type {
45
+ AnyMapoToolSpec,
46
+ MapoToolContext,
47
+ } from "./runtime/core/tool-spec.js";
48
+ import type { ApiKnowledge, DocsKnowledge } from "./runtime/core/types.js";
49
+
50
+ function readVersion(): string {
51
+ try {
52
+ const pkg = JSON.parse(
53
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8"),
54
+ );
55
+ return String(pkg.version ?? "0.0.0");
56
+ } catch {
57
+ return "0.0.0";
58
+ }
59
+ }
60
+
61
+ /** Default endpoint of the Nuxt module, overridable with `--app`. */
62
+ export const DEFAULT_APP_URL = mcpEndpointUrl("http://localhost:3000");
63
+
64
+ /** All tools that run without the Nuxt dev server. */
65
+ function staticTools(): AnyMapoToolSpec[] {
66
+ return [...docsTools, ...apiTools, ...scaffoldTools, ...backendTools];
67
+ }
68
+
69
+ function createToolContext(
70
+ knowledgeDir: string | null,
71
+ rootDir: string,
72
+ schemaUrl: string | null = null,
73
+ ): MapoToolContext {
74
+ let docs: DocsKnowledge | null = null;
75
+ let api: ApiKnowledge | null = null;
76
+ return {
77
+ knowledge: () => (docs ??= loadDocsKnowledge(knowledgeDir)),
78
+ api: () => (api ??= loadApiKnowledge(knowledgeDir)),
79
+ // The CLI has no app of its own; live tools are forwarded instead.
80
+ manifest: () => null,
81
+ // The editor spawns this process inside the project, so the working
82
+ // directory is the project — reported back on every write so a wrong root
83
+ // is visible immediately.
84
+ rootDir: () => rootDir,
85
+ canWrite: () => true,
86
+ // No nuxt.config to read: the CLI takes the schema from a flag or the env.
87
+ backend: () => ({
88
+ schemaUrl: schemaUrl ?? process.env.MAPO_BACKEND_SCHEMA_URL ?? null,
89
+ token: process.env.MAPO_BACKEND_TOKEN ?? null,
90
+ }),
91
+ };
92
+ }
93
+
94
+ function textOf(result: unknown): string {
95
+ const content =
96
+ (result as { content?: Array<{ type: string; text?: string }> }).content ??
97
+ [];
98
+ return content
99
+ .filter((part) => part.type === "text" && part.text)
100
+ .map((part) => part.text)
101
+ .join("\n");
102
+ }
103
+
104
+ /**
105
+ * Forwards a live tool call to the app's own MCP endpoint.
106
+ *
107
+ * The connection is lazy and re-established on demand: the dev server is
108
+ * routinely started *after* the editor spawned this process, and it restarts
109
+ * whenever nuxt.config changes. A failure is reported as an actionable message
110
+ * rather than an error, because "the dev server is down" is a normal state.
111
+ */
112
+ function createAppProxy(appUrl: string) {
113
+ let client: Client | null = null;
114
+
115
+ return async function forward(
116
+ name: string,
117
+ args: Record<string, unknown>,
118
+ ): Promise<string> {
119
+ try {
120
+ if (!client) {
121
+ const candidate = new Client({
122
+ name: "mapo-mcp-cli",
123
+ version: readVersion(),
124
+ });
125
+ await candidate.connect(
126
+ new StreamableHTTPClientTransport(new URL(appUrl)),
127
+ );
128
+ client = candidate;
129
+ }
130
+ return textOf(await client.callTool({ name, arguments: args }));
131
+ } catch (error) {
132
+ client = null; // drop the dead connection so the next call retries
133
+ const message = error instanceof Error ? error.message : String(error);
134
+ return (
135
+ `\`${name}\` needs the running app, and ${appUrl} is not answering (${message}).\n\n` +
136
+ "Start the dev server (`pnpm dev`) and call the tool again. If the app runs on another " +
137
+ "port, behind a proxy or under an `app.baseURL`, pass its endpoint with `--app` or " +
138
+ "`MAPO_MCP_APP_URL` (for example `http://localhost/backoffice/mcp/mapo`): the dev server " +
139
+ "prints it at startup. Documentation and API tools work without it."
140
+ );
141
+ }
142
+ };
143
+ }
144
+
145
+ export async function createStdioServer(
146
+ knowledgeDir: string | null,
147
+ appUrl: string = DEFAULT_APP_URL,
148
+ rootDir: string = process.cwd(),
149
+ schemaUrl: string | null = null,
150
+ ): Promise<McpServer> {
151
+ const server = new McpServer(
152
+ { name: "mapo", version: readVersion() },
153
+ { instructions: MAPO_INSTRUCTIONS },
154
+ );
155
+
156
+ const context = createToolContext(knowledgeDir, rootDir, schemaUrl);
157
+
158
+ for (const spec of staticTools()) {
159
+ server.registerTool(
160
+ spec.name,
161
+ {
162
+ title: spec.title,
163
+ description: spec.description,
164
+ inputSchema: spec.inputSchema,
165
+ ...(spec.annotations ? { annotations: spec.annotations } : {}),
166
+ },
167
+ async (args: Record<string, unknown>) => {
168
+ try {
169
+ const text = await spec.run(args, context);
170
+ return { content: [{ type: "text" as const, text }] };
171
+ } catch (error) {
172
+ const message =
173
+ error instanceof Error ? error.message : String(error);
174
+ return {
175
+ content: [{ type: "text" as const, text: message }],
176
+ isError: true,
177
+ };
178
+ }
179
+ },
180
+ );
181
+ }
182
+
183
+ // Live tools keep their schema and description here, but the app answers.
184
+ const forward = createAppProxy(appUrl);
185
+
186
+ for (const spec of appTools) {
187
+ server.registerTool(
188
+ spec.name,
189
+ {
190
+ title: spec.title,
191
+ description: spec.description,
192
+ inputSchema: spec.inputSchema,
193
+ ...(spec.annotations ? { annotations: spec.annotations } : {}),
194
+ },
195
+ async (args: Record<string, unknown>) => ({
196
+ content: [
197
+ { type: "text" as const, text: await forward(spec.name, args) },
198
+ ],
199
+ }),
200
+ );
201
+ }
202
+
203
+ registerResources(server, context);
204
+ registerPrompts(server);
205
+ return server;
206
+ }
207
+
208
+ /** The same slash-commands the Nuxt handler exposes. */
209
+ function registerPrompts(server: McpServer): void {
210
+ for (const prompt of PROMPTS) {
211
+ server.registerPrompt(
212
+ prompt.name,
213
+ {
214
+ title: prompt.title,
215
+ description: prompt.description,
216
+ argsSchema: prompt.argsSchema,
217
+ },
218
+ // Same widening as the Nitro adapter: the SDK infers `unknown` from a
219
+ // generic shape, and zod has already validated the arguments.
220
+ (args: Record<string, unknown>) => ({
221
+ messages: [
222
+ {
223
+ role: "user" as const,
224
+ content: {
225
+ type: "text" as const,
226
+ text: prompt.render(args as Record<string, string | undefined>),
227
+ },
228
+ },
229
+ ],
230
+ }),
231
+ );
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Same resources as the Nuxt handler, minus `mapo://app/manifest`: the CLI has
237
+ * no running app to describe.
238
+ */
239
+ function registerResources(server: McpServer, context: MapoToolContext): void {
240
+ const markdown = (uri: URL, text: string) => ({
241
+ contents: [{ uri: uri.toString(), mimeType: "text/markdown", text }],
242
+ });
243
+
244
+ server.registerResource(
245
+ "mapo-knowledge-index",
246
+ INDEX_URI,
247
+ {
248
+ title: "Mapo knowledge index",
249
+ description:
250
+ "Recipes, documentation pages, components, field types and composables known to this server.",
251
+ mimeType: "text/markdown",
252
+ },
253
+ (uri) =>
254
+ markdown(uri, renderKnowledgeIndex(context.knowledge(), context.api())),
255
+ );
256
+
257
+ server.registerResource(
258
+ "mapo-overview",
259
+ OVERVIEW_URI,
260
+ {
261
+ title: "Mapo overview",
262
+ description:
263
+ "How Mapo fits together: the packages, the backend contract, declarative pages, the form engine and the customization layers.",
264
+ mimeType: "text/markdown",
265
+ },
266
+ (uri) => markdown(uri, renderOverview(context.knowledge())),
267
+ );
268
+
269
+ server.registerResource(
270
+ "mapo-doc",
271
+ new ResourceTemplate(`${DOCS_URI_PREFIX}{+path}`, {
272
+ list: () => ({ resources: docResourceList(context.knowledge()) }),
273
+ }),
274
+ {
275
+ title: "Mapo documentation page",
276
+ description: "A full documentation page, addressed by its path.",
277
+ mimeType: "text/markdown",
278
+ },
279
+ (uri, variables) => {
280
+ const raw = variables.path;
281
+ const path = Array.isArray(raw) ? raw.join("/") : (raw ?? "");
282
+ const text = renderDocResource(
283
+ context.knowledge(),
284
+ decodeURIComponent(path),
285
+ );
286
+ return markdown(uri, text ?? `No documentation page at "${path}".`);
287
+ },
288
+ );
289
+
290
+ server.registerResource(
291
+ "mapo-field-type",
292
+ new ResourceTemplate(`${FIELD_URI_PREFIX}{type}`, {
293
+ list: () => ({ resources: fieldResourceList(context.api()) }),
294
+ }),
295
+ {
296
+ title: "Mapo form field type",
297
+ description:
298
+ "The component, attrs and descriptor contract of a field type.",
299
+ mimeType: "text/markdown",
300
+ },
301
+ (uri, variables) => {
302
+ const raw = variables.type;
303
+ const type = Array.isArray(raw) ? raw[0]! : (raw ?? "");
304
+ const text = renderFieldResource(context.api(), decodeURIComponent(type));
305
+ return markdown(uri, text ?? `No field type "${type}" is registered.`);
306
+ },
307
+ );
308
+ }
309
+
310
+ const serve = defineCommand({
311
+ meta: {
312
+ name: "serve",
313
+ description: "Run the Mapo MCP server on stdio (for IDE/agent clients)",
314
+ },
315
+ args: {
316
+ knowledge: {
317
+ type: "string",
318
+ description:
319
+ "Path to a prebuilt knowledge directory (defaults to the bundled one)",
320
+ },
321
+ app: {
322
+ type: "string",
323
+ description: `MCP endpoint of the running app, for the live tools (default ${DEFAULT_APP_URL})`,
324
+ },
325
+ root: {
326
+ type: "string",
327
+ description:
328
+ "Project root for scaffolding (default: the working directory)",
329
+ },
330
+ },
331
+ async run({ args }) {
332
+ const knowledgeDir = args.knowledge
333
+ ? String(args.knowledge)
334
+ : resolveKnowledgeDir();
335
+
336
+ if (!knowledgeDir) {
337
+ console.error(
338
+ "[mapo-mcp] knowledge base not found — docs tools will fail. " +
339
+ "Build it with `pnpm --filter @mapomodule/mcp build`.",
340
+ );
341
+ }
342
+
343
+ const appUrl = String(
344
+ args.app ?? process.env.MAPO_MCP_APP_URL ?? DEFAULT_APP_URL,
345
+ );
346
+
347
+ const rootDir = String(args.root ?? process.cwd());
348
+ const schemaUrl = args.schema ? String(args.schema) : null;
349
+ const server = await createStdioServer(
350
+ knowledgeDir,
351
+ appUrl,
352
+ rootDir,
353
+ schemaUrl,
354
+ );
355
+ await server.connect(new StdioServerTransport());
356
+ console.error(
357
+ `[mapo-mcp] ready on stdio (${staticTools().length} tools, ` +
358
+ `${appTools.length} forwarded to ${appUrl})`,
359
+ );
360
+ },
361
+ });
362
+
363
+ const main = defineCommand({
364
+ meta: {
365
+ name: "mapo-mcp",
366
+ version: readVersion(),
367
+ description: "Mapo MCP server and IDE integration helper",
368
+ },
369
+ subCommands: { serve },
370
+ // Bare `mapo-mcp` behaves like `mapo-mcp serve`: MCP clients spawn the bin
371
+ // with no arguments.
372
+ run: (context) => serve.run?.(context as never),
373
+ });
374
+
375
+ runMain(main);
package/src/index.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Public types for `@mapomodule/mcp`.
3
+ * Import from `@mapomodule/mcp/types`.
4
+ */
5
+
6
+ export interface MapoMcpBackendOptions {
7
+ /**
8
+ * OpenAPI/DRF schema URL used by `mapo_backend_schema`
9
+ * (e.g. `http://localhost:8000/api/schema/?format=json`).
10
+ * Falls back to `MAPO_BACKEND_SCHEMA_URL`.
11
+ */
12
+ schemaUrl?: string;
13
+ /**
14
+ * Name of the environment variable holding the bearer token for the schema
15
+ * request. The value is never echoed back to the MCP client.
16
+ * @default "MAPO_BACKEND_TOKEN"
17
+ */
18
+ tokenEnv?: string;
19
+ }
20
+
21
+ export interface MapoMcpOptions {
22
+ /**
23
+ * Register the MCP server. Defaults to `nuxt.options.dev` — the server is a
24
+ * development tool and never ships in a production build unless forced.
25
+ */
26
+ enabled?: boolean;
27
+ backend?: MapoMcpBackendOptions;
28
+ }
29
+
30
+ /** Field type registered in the form registry, as seen at build time. */
31
+ export interface MapoManifestFieldType {
32
+ type: string;
33
+ source: "default" | "config";
34
+ }
35
+
36
+ /** Build-time snapshot of the consuming app, exposed by `mapo_inspect_app`. */
37
+ export interface MapoAppManifest {
38
+ /** Absolute path of the app root (dev machine). */
39
+ rootDir: string;
40
+ dev: boolean;
41
+ /** Installed `@mapomodule/*` modules and their versions. */
42
+ modules: Array<{ name: string; version?: string }>;
43
+ /**
44
+ * `modules[]` as written in `nuxt.config`, in order. Only string entries are
45
+ * reported — inline function modules have no stable name. Ordering matters:
46
+ * `@nuxt/ui` must come before `mapomodule`.
47
+ */
48
+ moduleOrder: string[];
49
+ /** Public Mapo runtime config; secret values are replaced by their key names. */
50
+ config: Record<string, unknown>;
51
+ fieldTypes: MapoManifestFieldType[];
52
+ components: string[];
53
+ routes: Array<{ path: string; file?: string }>;
54
+ locales: string[];
55
+ }
56
+
57
+ /** Payload of the `#mapo-mcp/context.mjs` virtual server module. */
58
+ export interface MapoMcpContext {
59
+ /** Absolute path of the generated knowledge base, or `null` when not built. */
60
+ knowledgeDir: string | null;
61
+ backend: Required<Pick<MapoMcpBackendOptions, "tokenEnv">> & {
62
+ schemaUrl: string | null;
63
+ };
64
+ manifest: MapoAppManifest;
65
+ }
package/src/module.ts ADDED
@@ -0,0 +1,213 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import {
4
+ addServerTemplate,
5
+ createResolver,
6
+ defineNuxtModule,
7
+ hasNuxtModule,
8
+ installModule,
9
+ logger,
10
+ } from "@nuxt/kit";
11
+ import type { NuxtModule } from "@nuxt/schema";
12
+ import type { MapoAppManifest, MapoMcpContext, MapoMcpOptions } from "./index";
13
+ import { mcpEndpointUrl } from "./runtime/core/endpoint";
14
+
15
+ export type { MapoAppManifest, MapoMcpContext, MapoMcpOptions } from "./index";
16
+
17
+ /** Shape of the paths object passed by `@nuxtjs/mcp-toolkit`'s build-time hook. */
18
+ interface McpDefinitionPaths {
19
+ tools: string[];
20
+ resources: string[];
21
+ prompts: string[];
22
+ handlers: string[];
23
+ }
24
+
25
+ /**
26
+ * Config keys owned by other modules. They are augmented onto `NuxtOptions`
27
+ * only inside the consuming app's build, so this module reads them structurally.
28
+ */
29
+ interface ForeignModuleOptions {
30
+ mapoForm?: { fields?: { mapping?: Record<string, unknown> } };
31
+ i18n?: { locales?: Array<string | { code: string }> };
32
+ }
33
+
34
+ /** Reads the field types extracted from the form registry at build time. */
35
+ function readDefaultFieldTypes(knowledgeDir: string | null): string[] {
36
+ if (!knowledgeDir) return [];
37
+ const file = join(knowledgeDir, "api.json");
38
+ if (!existsSync(file)) return [];
39
+ try {
40
+ const parsed = JSON.parse(readFileSync(file, "utf-8")) as {
41
+ fieldTypes?: Array<{ type: string }>;
42
+ };
43
+ return (parsed.fieldTypes ?? []).map((entry) => entry.type);
44
+ } catch {
45
+ return [];
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Mapo MCP server — development-only.
51
+ *
52
+ * Registers a dedicated `@nuxtjs/mcp-toolkit` handler (default route `/mcp/mapo`)
53
+ * carrying Mapo's docs, API surface, app introspection and scaffolding tools.
54
+ * The definitions live inside this package and are injected through the
55
+ * toolkit's `mcp:definitions:paths` hook, so consuming apps write no MCP files
56
+ * and their own MCP definitions stay untouched.
57
+ */
58
+ export default defineNuxtModule<MapoMcpOptions>({
59
+ meta: {
60
+ name: "@mapomodule/mcp",
61
+ configKey: "mapoMcp",
62
+ },
63
+
64
+ defaults: {},
65
+
66
+ async setup(options, nuxt) {
67
+ const log = logger.withTag("mapo:mcp");
68
+ const enabled = options.enabled ?? nuxt.options.dev;
69
+ if (!enabled) return;
70
+
71
+ const resolver = createResolver(import.meta.url);
72
+
73
+ // `dist/knowledge` when built, `../dist/knowledge` when running the jiti stub.
74
+ const knowledgeDir = ["./knowledge", "../knowledge", "../dist/knowledge"]
75
+ .map((candidate) => resolver.resolve(candidate))
76
+ .find((candidate) => existsSync(join(candidate, "docs.json")));
77
+
78
+ if (!knowledgeDir) {
79
+ log.warn(
80
+ "Knowledge base missing — docs tools will fail. Build it with `pnpm --filter @mapomodule/mcp build`.",
81
+ );
82
+ }
83
+
84
+ if (!hasNuxtModule("@nuxtjs/mcp-toolkit")) {
85
+ await installModule(await resolver.resolvePath("@nuxtjs/mcp-toolkit"), {
86
+ name: "Mapo",
87
+ description:
88
+ "Mapo admin framework: docs, APIs, app introspection and scaffolding.",
89
+ });
90
+ }
91
+
92
+ // Ship our definitions from inside the package: the toolkit resolves each
93
+ // path against every layer's `server/` dir, and an absolute path wins.
94
+ // Pushing the parent of `handlers/` gives us the named handler `mapo`
95
+ // (route `<mcp.route>/mapo`) with its own tools, resources and prompts.
96
+ // `mcp:definitions:paths` is not augmented onto NuxtHooks by the toolkit,
97
+ // so the listener is registered through a locally typed view of `hook`.
98
+ const hook = nuxt.hook as unknown as (
99
+ name: "mcp:definitions:paths",
100
+ listener: (paths: McpDefinitionPaths) => void,
101
+ ) => void;
102
+
103
+ hook("mcp:definitions:paths", (paths) => {
104
+ // `runtime/mcp` must contain nothing but `handlers/`: the toolkit loads
105
+ // every top-level file of a scanned path as a handler definition.
106
+ paths.handlers.push(resolver.resolve("./runtime/mcp"));
107
+ });
108
+
109
+ // Build-time app snapshot, filled in by the hooks below and serialised when
110
+ // Nitro renders the virtual module.
111
+ const components: string[] = [];
112
+ const routes: MapoAppManifest["routes"] = [];
113
+
114
+ nuxt.hook("components:extend", (registered) => {
115
+ components.length = 0;
116
+ for (const component of registered) {
117
+ if (component.pascalName?.startsWith("Mapo"))
118
+ components.push(component.pascalName);
119
+ }
120
+ components.sort();
121
+ });
122
+
123
+ nuxt.hook("pages:extend", (pages) => {
124
+ routes.length = 0;
125
+ const walk = (list: typeof pages) => {
126
+ for (const page of list) {
127
+ routes.push({
128
+ path: page.path,
129
+ ...(page.file ? { file: page.file } : {}),
130
+ });
131
+ if (page.children?.length) walk(page.children);
132
+ }
133
+ };
134
+ walk(pages);
135
+ });
136
+
137
+ const buildContext = (): MapoMcpContext => {
138
+ const publicConfig = nuxt.options.runtimeConfig.public as Record<
139
+ string,
140
+ unknown
141
+ >;
142
+ const mapoConfig = Object.fromEntries(
143
+ Object.entries(publicConfig).filter(([key]) =>
144
+ key.toLowerCase().startsWith("mapo"),
145
+ ),
146
+ );
147
+
148
+ // Read foreign module config keys structurally: their types are only
149
+ // augmented onto NuxtOptions inside the consuming app's build.
150
+ const options_ = nuxt.options as unknown as ForeignModuleOptions;
151
+ const configuredTypes = Object.keys(
152
+ options_.mapoForm?.fields?.mapping ?? {},
153
+ );
154
+ const defaultTypes = readDefaultFieldTypes(knowledgeDir ?? null);
155
+
156
+ const manifest: MapoAppManifest = {
157
+ rootDir: nuxt.options.rootDir,
158
+ dev: nuxt.options.dev,
159
+ modules: (nuxt.options._installedModules ?? [])
160
+ .map((installed) => ({
161
+ name: installed.meta?.name ?? "",
162
+ ...(installed.meta?.version
163
+ ? { version: installed.meta.version }
164
+ : {}),
165
+ }))
166
+ .filter((entry) => entry.name.includes("mapo")),
167
+ // Declaration order, not resolution order: `mapo_doctor` checks that
168
+ // `@nuxt/ui` is registered before `mapomodule`.
169
+ moduleOrder: (nuxt.options.modules ?? []).filter(
170
+ (entry): entry is string => typeof entry === "string",
171
+ ),
172
+ config: mapoConfig,
173
+ fieldTypes: [
174
+ ...defaultTypes.map((type) => ({ type, source: "default" as const })),
175
+ ...configuredTypes
176
+ .filter((type) => !defaultTypes.includes(type))
177
+ .map((type) => ({ type, source: "config" as const })),
178
+ ],
179
+ components: [...components],
180
+ routes: [...routes],
181
+ locales: (options_.i18n?.locales ?? []).map((locale) =>
182
+ typeof locale === "string" ? locale : locale.code,
183
+ ),
184
+ };
185
+
186
+ return {
187
+ knowledgeDir: knowledgeDir ?? null,
188
+ backend: {
189
+ schemaUrl:
190
+ options.backend?.schemaUrl ??
191
+ process.env.MAPO_BACKEND_SCHEMA_URL ??
192
+ null,
193
+ tokenEnv: options.backend?.tokenEnv ?? "MAPO_BACKEND_TOKEN",
194
+ },
195
+ manifest,
196
+ };
197
+ };
198
+
199
+ addServerTemplate({
200
+ filename: "#mapo-mcp/context.mjs",
201
+ getContents: () => `export default ${JSON.stringify(buildContext())}`,
202
+ });
203
+
204
+ // Nitro serves the handler under `app.baseURL`: print the URL it really
205
+ // answers on, which is what an HTTP client or `mapo-mcp serve --app` needs.
206
+ log.info(
207
+ `MCP server available at ${mcpEndpointUrl(
208
+ nuxt.options.devServer?.url ?? "http://localhost:3000",
209
+ nuxt.options.app.baseURL,
210
+ )}`,
211
+ );
212
+ },
213
+ }) satisfies NuxtModule<MapoMcpOptions>;