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

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