@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
@@ -0,0 +1,143 @@
1
+ import { z } from "zod";
2
+ import {
3
+ listModels,
4
+ renderFields,
5
+ resolveSchema,
6
+ toFields,
7
+ toScaffoldSpecs
8
+ } from "../openapi.js";
9
+ import {
10
+ SchemaUnavailableError,
11
+ loadOpenApiDocument
12
+ } from "../schema-source.js";
13
+ import { defineMapoTool } from "../tool-spec.js";
14
+ const READ_ONLY = {
15
+ readOnlyHint: true,
16
+ destructiveHint: false,
17
+ idempotentHint: true,
18
+ // It reaches a backend that is not part of this server.
19
+ openWorldHint: true
20
+ };
21
+ const NO_SOURCE = "No schema source configured.\n\nSet `mapo.mcp.backend.schemaUrl` in nuxt.config (drf-spectacular: `http://localhost:8000/api/schema/?format=json`), export `MAPO_BACKEND_SCHEMA_URL`, or pass `url` to this tool. A local path to an exported schema works too.";
22
+ export const backendSchemaTool = defineMapoTool({
23
+ name: "mapo_backend_schema",
24
+ title: "Backend schema \u2192 Mapo fields",
25
+ description: "Read the backend's OpenAPI/DRF schema and turn a serializer into Mapo field descriptors: types, choices, required and read-only flags, and the endpoint of every relation. Use it before writing a form against a real API, and feed its output to mapo_scaffold.",
26
+ inputSchema: {
27
+ action: z.enum(["list_models", "describe_model", "to_fields"]).describe(
28
+ "list the serializers, inspect one, or map one to field descriptors"
29
+ ),
30
+ model: z.string().optional().describe("Component name, e.g. 'Article'"),
31
+ url: z.string().optional().describe(
32
+ "Schema URL or local file path; defaults to the configured source"
33
+ ),
34
+ includeReadOnly: z.boolean().optional().describe(
35
+ "Keep server-computed properties (id, timestamps) as readonly fields"
36
+ )
37
+ },
38
+ annotations: READ_ONLY,
39
+ inputExamples: [
40
+ { action: "list_models" },
41
+ { action: "to_fields", model: "Article" }
42
+ ],
43
+ run: async (args, context) => {
44
+ const backend = context.backend();
45
+ const source = args.url ?? backend.schemaUrl;
46
+ if (!source) return NO_SOURCE;
47
+ let document;
48
+ try {
49
+ document = await loadOpenApiDocument(source, {
50
+ token: backend.token,
51
+ rootDir: context.rootDir()
52
+ });
53
+ } catch (error) {
54
+ if (error instanceof SchemaUnavailableError) return error.message;
55
+ throw error;
56
+ }
57
+ const title = document.info?.title ? `${document.info.title} \u2014 ` : "";
58
+ if (args.action === "list_models") {
59
+ const models = listModels(document);
60
+ if (!models.length) return `${source} declares no component schemas.`;
61
+ const lines = models.map(
62
+ (model) => `- \`${model.name}\` (${model.fieldCount} properties)` + (model.endpoint ? ` \u2192 \`${model.endpoint}\`` : " \u2014 no list endpoint declared")
63
+ );
64
+ return `# ${title}${models.length} models
65
+ source: \`${source}\`
66
+
67
+ ${lines.join("\n")}
68
+
69
+ Call this tool again with \`action: "to_fields"\` and a model name.`;
70
+ }
71
+ if (!args.model) {
72
+ return `\`${args.action}\` needs a \`model\`. Run \`action: "list_models"\` to see what exists.`;
73
+ }
74
+ const schema = document.components?.schemas?.[args.model];
75
+ if (!schema) {
76
+ const available = listModels(document).map((model) => model.name).slice(0, 30).join(", ");
77
+ return `No model \`${args.model}\` in ${source}. Available: ${available}.`;
78
+ }
79
+ if (args.action === "describe_model") {
80
+ const required = new Set(schema.required ?? []);
81
+ const rows = Object.entries(schema.properties ?? {}).map(
82
+ ([key, property]) => {
83
+ const { schema: resolved, ref } = resolveSchema(document, property);
84
+ const kind = ref ?? resolved.type ?? "unknown";
85
+ const flags = [
86
+ required.has(key) ? "required" : "",
87
+ resolved.readOnly ? "read-only" : "",
88
+ resolved.nullable ? "nullable" : "",
89
+ resolved.enum?.length ? `enum(${resolved.enum.length})` : ""
90
+ ].filter(Boolean).join(", ");
91
+ return `- \`${key}\`: ${kind}${resolved.format ? ` (${resolved.format})` : ""}${flags ? ` \u2014 ${flags}` : ""}`;
92
+ }
93
+ );
94
+ return `# ${args.model}
95
+ source: \`${source}\`
96
+ ` + (schema.description ? `
97
+ ${schema.description}
98
+ ` : "") + `
99
+ ${rows.join("\n") || "(no properties)"}
100
+
101
+ Map it with \`action: "to_fields"\`.`;
102
+ }
103
+ const knownTypes = new Set(
104
+ context.api().fieldTypes.map((field) => field.type)
105
+ );
106
+ const result = toFields(document, args.model, {
107
+ knownTypes,
108
+ ...args.includeReadOnly ? { includeReadOnly: true } : {}
109
+ });
110
+ const skipped = result.skipped.length ? `
111
+ ## Skipped
112
+ ${result.skipped.map((entry) => `- \`${entry.key}\` \u2014 ${entry.reason}`).join("\n")}
113
+ ` : "";
114
+ const notes = result.notes.length ? `
115
+ ${result.notes.map((note) => `- ${note}`).join("\n")}
116
+ ` : "";
117
+ const specs = toScaffoldSpecs(result);
118
+ const scaffoldLine = specs.length ? `
119
+ ## Scaffold it
120
+ \`\`\`json
121
+ ${JSON.stringify(
122
+ {
123
+ kind: "detail-page",
124
+ name: args.model.toLowerCase(),
125
+ ...result.endpoint ? { endpoint: result.endpoint } : {},
126
+ fields: specs
127
+ },
128
+ null,
129
+ 2
130
+ )}
131
+ \`\`\`
132
+ Pass that to mapo_scaffold.
133
+ ` : "";
134
+ return `# ${args.model} \u2192 ${result.fields.length} field descriptors
135
+ source: \`${source}\`${result.endpoint ? ` \xB7 endpoint: \`${result.endpoint}\`` : ""}
136
+
137
+ \`\`\`ts
138
+ ${renderFields(result)}
139
+ \`\`\`
140
+ ` + skipped + notes + scaffoldLine + "\nTypes were checked against the registry of this app: a property whose mapping is not registered is skipped rather than emitted.";
141
+ }
142
+ });
143
+ export const backendTools = [backendSchemaTool];
File without changes
@@ -0,0 +1,150 @@
1
+ import { z } from "zod";
2
+ import { matchRecipes, RECIPES } from "../recipes.js";
3
+ import { getDoc, searchDocs } from "../search.js";
4
+ import { defineMapoTool } from "../tool-spec.js";
5
+ function renderRecipes(recipes) {
6
+ if (!recipes.length) return "";
7
+ const lines = recipes.map((recipe) => {
8
+ const section = recipe.heading ? ` (section "${recipe.heading}")` : "";
9
+ const seeAlso = recipe.seeAlso?.length ? `
10
+ see also: ${recipe.seeAlso.join(", ")}` : "";
11
+ return `- **${recipe.task}** \u2192 \`${recipe.doc}\`${section}
12
+ ${recipe.summary}${seeAlso}`;
13
+ });
14
+ return `## Canonical recipe${recipes.length > 1 ? "s" : ""} for this task
15
+ ${lines.join("\n")}
16
+
17
+ `;
18
+ }
19
+ const SECTIONS = [
20
+ "howto",
21
+ "guide",
22
+ "uikit",
23
+ "form",
24
+ "modules",
25
+ "migration"
26
+ ];
27
+ export const searchDocsTool = defineMapoTool({
28
+ name: "mapo_search_docs",
29
+ title: "Search Mapo documentation",
30
+ description: "Search the official Mapo documentation and return the most relevant sections (never whole files). Use this before writing any Mapo code; follow up with mapo_get_doc to read a full section.",
31
+ inputSchema: {
32
+ query: z.string().describe(
33
+ "Natural-language question or keywords, e.g. 'paginated list with filters'"
34
+ ),
35
+ section: z.enum(SECTIONS).optional().describe("Restrict to one docs area"),
36
+ pkg: z.string().optional().describe("Restrict to a package, e.g. '@mapomodule/form' or 'uikit'"),
37
+ limit: z.number().int().min(1).max(20).optional().describe("Number of sections to return (default 5)")
38
+ },
39
+ annotations: {
40
+ readOnlyHint: true,
41
+ destructiveHint: false,
42
+ idempotentHint: true,
43
+ openWorldHint: false
44
+ },
45
+ inputExamples: [
46
+ { query: "CRUD list with filters and bulk actions" },
47
+ { query: "custom form field registration", section: "form" }
48
+ ],
49
+ run: (args, context) => {
50
+ const hits = searchDocs(context.knowledge(), args.query, {
51
+ ...args.section ? { section: args.section } : {},
52
+ ...args.pkg ? { pkg: args.pkg } : {},
53
+ ...args.limit ? { limit: args.limit } : {}
54
+ });
55
+ const recipes = renderRecipes(matchRecipes(args.query));
56
+ if (!hits.length) {
57
+ return recipes ? `${recipes}No section matched the keywords, but the recipe above covers this task.` : `No documentation section matched "${args.query}". Try fewer or more general keywords, or drop the section filter.`;
58
+ }
59
+ const body = hits.map(
60
+ (hit, position) => `### ${position + 1}. ${hit.title} \u2014 ${hit.heading}
61
+ path: \`${hit.path}\`${hit.anchor ? ` \xB7 anchor: \`#${hit.anchor}\`` : ""} \xB7 score: ${hit.score}
62
+ ` + (hit.tags.length ? `symbols: ${hit.tags.join(", ")}
63
+ ` : "") + `
64
+ ${hit.snippet}
65
+ `
66
+ ).join("\n---\n\n");
67
+ return `${recipes}${hits.length} matching section(s) for "${args.query}":
68
+
69
+ ${body}
70
+ ---
71
+ Read a full section with mapo_get_doc({ path, heading }).`;
72
+ }
73
+ });
74
+ export const getDocTool = defineMapoTool({
75
+ name: "mapo_get_doc",
76
+ title: "Read a Mapo documentation page",
77
+ description: "Return the exact markdown of a documentation page, or of one of its sections when `heading` is given. Paths come from mapo_search_docs (e.g. 'howto/crud-list.md').",
78
+ inputSchema: {
79
+ path: z.string().describe(
80
+ "Doc path relative to the docs root, e.g. 'howto/crud-detail.md'"
81
+ ),
82
+ heading: z.string().optional().describe(
83
+ "Section heading or anchor to return instead of the whole page"
84
+ ),
85
+ maxChars: z.number().int().min(500).max(4e4).optional().describe("Truncation limit (default 8000)")
86
+ },
87
+ annotations: {
88
+ readOnlyHint: true,
89
+ destructiveHint: false,
90
+ idempotentHint: true,
91
+ openWorldHint: false
92
+ },
93
+ inputExamples: [
94
+ { path: "howto/crud-list.md" },
95
+ { path: "uikit/form/validation.md", heading: "Async validation" }
96
+ ],
97
+ run: (args, context) => {
98
+ const doc = getDoc(context.knowledge(), args.path, {
99
+ ...args.heading ? { heading: args.heading } : {},
100
+ ...args.maxChars ? { maxChars: args.maxChars } : {}
101
+ });
102
+ if (!doc) {
103
+ return `No such documentation page: "${args.path}". Use mapo_search_docs to find the correct path.`;
104
+ }
105
+ return `# ${doc.title}
106
+ source: \`${doc.path}\`
107
+ sections: ${doc.headings.join(" \xB7 ") || "(none)"}
108
+
109
+ ${doc.content}`;
110
+ }
111
+ });
112
+ export const listRecipesTool = defineMapoTool({
113
+ name: "mapo_list_recipes",
114
+ title: "List Mapo task recipes",
115
+ description: "List the canonical Mapo recipes (task \u2192 documentation page). Call this to discover what Mapo can do out of the box before designing a solution, or pass `task` to find the recipe for a goal.",
116
+ inputSchema: {
117
+ task: z.string().optional().describe(
118
+ "Goal in plain words, e.g. 'let editors reorder navigation entries'"
119
+ )
120
+ },
121
+ annotations: {
122
+ readOnlyHint: true,
123
+ destructiveHint: false,
124
+ idempotentHint: true,
125
+ openWorldHint: false
126
+ },
127
+ inputExamples: [{}, { task: "upload images and pick them in a form" }],
128
+ run: (args) => {
129
+ if (args.task) {
130
+ const matches = matchRecipes(args.task, 3);
131
+ if (!matches.length) {
132
+ return `No curated recipe matches "${args.task}". Fall back to mapo_search_docs, or call mapo_list_recipes with no argument to see every recipe.`;
133
+ }
134
+ return `${renderRecipes(matches)}Read the page with mapo_get_doc({ path }).`;
135
+ }
136
+ const lines = RECIPES.map(
137
+ (recipe) => `- **${recipe.task}** \u2192 \`${recipe.doc}\` \u2014 ${recipe.summary}`
138
+ );
139
+ return `${RECIPES.length} Mapo recipes:
140
+
141
+ ${lines.join("\n")}
142
+
143
+ Read one with mapo_get_doc({ path }).`;
144
+ }
145
+ });
146
+ export const docsTools = [
147
+ searchDocsTool,
148
+ getDocTool,
149
+ listRecipesTool
150
+ ];
File without changes
@@ -0,0 +1,127 @@
1
+ import { z } from "zod";
2
+ import {
3
+ SCAFFOLD_DESCRIPTIONS,
4
+ SCAFFOLD_KINDS,
5
+ UnknownFieldTypeError,
6
+ scaffold
7
+ } from "../scaffold/index.js";
8
+ import { defineMapoTool } from "../tool-spec.js";
9
+ import { writeScaffold } from "../write.js";
10
+ function languageOf(path) {
11
+ if (path.endsWith(".vue")) return "vue";
12
+ if (path.endsWith(".ts")) return "ts";
13
+ if (path.endsWith(".css")) return "css";
14
+ return "";
15
+ }
16
+ const KIND_LIST = SCAFFOLD_KINDS.map(
17
+ (kind) => `\`${kind}\` (${SCAFFOLD_DESCRIPTIONS[kind]})`
18
+ ).join(", ");
19
+ export const scaffoldTool = defineMapoTool({
20
+ name: "mapo_scaffold",
21
+ title: "Scaffold Mapo code",
22
+ description: `Generate Mapo code that follows the framework's canonical patterns: list and detail pages, standalone forms, custom field types, login page, theming, backend proxy, menu and media pages. Returns the files for review; pass \`write: true\` to create them in the project. Kinds: ${KIND_LIST}.`,
23
+ inputSchema: {
24
+ kind: z.enum(SCAFFOLD_KINDS).describe("What to generate"),
25
+ name: z.string().optional().describe(
26
+ "Resource name, e.g. 'articles' \u2014 or the type name for custom-field"
27
+ ),
28
+ endpoint: z.string().optional().describe("REST endpoint (default `/api/<name>`)"),
29
+ route: z.string().optional().describe("Route base (default `/<name>`)"),
30
+ fields: z.array(z.string()).optional().describe(
31
+ "Field specs `key[:type[:label]]`, e.g. ['title:text:Title', 'body:editor']"
32
+ ),
33
+ write: z.boolean().optional().describe(
34
+ "Create the files instead of only showing them (development only)"
35
+ ),
36
+ overwrite: z.boolean().optional().describe("Allow replacing files that already exist")
37
+ },
38
+ annotations: {
39
+ // Not read-only: with `write` it creates files. Never destructive: existing
40
+ // files are refused unless `overwrite` is set.
41
+ readOnlyHint: false,
42
+ destructiveHint: false,
43
+ idempotentHint: true,
44
+ openWorldHint: false
45
+ },
46
+ inputExamples: [
47
+ {
48
+ kind: "list-page",
49
+ name: "articles",
50
+ fields: ["title:text:Title", "status:select:Status"]
51
+ },
52
+ {
53
+ kind: "detail-page",
54
+ name: "articles",
55
+ fields: ["title:text", "body:editor"],
56
+ write: true
57
+ },
58
+ { kind: "custom-field", name: "star-rating" }
59
+ ],
60
+ run: (args, context) => {
61
+ let result;
62
+ try {
63
+ result = scaffold({
64
+ kind: args.kind,
65
+ ...args.name ? { name: args.name } : {},
66
+ ...args.endpoint ? { endpoint: args.endpoint } : {},
67
+ ...args.route ? { route: args.route } : {},
68
+ ...args.fields ? { fields: args.fields } : {},
69
+ api: context.api()
70
+ });
71
+ } catch (error) {
72
+ if (error instanceof UnknownFieldTypeError) return error.message;
73
+ throw error;
74
+ }
75
+ const notes = result.notes.map((note) => `- ${note}`).join("\n");
76
+ const docs = result.docs.map((doc) => `\`${doc}\``).join(", ");
77
+ if (!args.write) {
78
+ const blocks = result.files.map(
79
+ (file) => `### \`${file.path}\`
80
+
81
+ \`\`\`${languageOf(file.path)}
82
+ ${file.content}\`\`\``
83
+ ).join("\n\n");
84
+ return `# ${SCAFFOLD_DESCRIPTIONS[args.kind]}
85
+
86
+ ${blocks}
87
+
88
+ ## Notes
89
+ ${notes}
90
+
91
+ Docs: ${docs}
92
+
93
+ Nothing was written. Call again with \`write: true\` to create these files.`;
94
+ }
95
+ const root = context.rootDir();
96
+ if (!root) {
97
+ return "Cannot write: the project root is unknown.\n\nConnect to the app's endpoint (`/mcp/mapo`) so the server knows where the project is, or run `mapo-mcp serve --root <path>`. The files above are unchanged.";
98
+ }
99
+ const outcomes = writeScaffold(result.files, {
100
+ root,
101
+ overwrite: args.overwrite ?? false,
102
+ allowed: context.canWrite()
103
+ });
104
+ const lines = outcomes.map((outcome) => {
105
+ const icon = outcome.status === "written" ? "\u2714" : "\u2716";
106
+ const detail = outcome.reason ? ` \u2014 ${outcome.reason}` : "";
107
+ return `- ${icon} \`${outcome.path}\` (${outcome.status})${detail}`;
108
+ });
109
+ const written = outcomes.filter(
110
+ (outcome) => outcome.status === "written"
111
+ ).length;
112
+ const blocked = outcomes.length - written;
113
+ return `# ${SCAFFOLD_DESCRIPTIONS[args.kind]}
114
+
115
+ Root: \`${root}\`
116
+
117
+ ${lines.join("\n")}
118
+
119
+ ` + (blocked ? `${blocked} file(s) were not written. Read the reason above; use \`overwrite: true\` only when replacing is intended.
120
+
121
+ ` : "") + `## Notes
122
+ ${notes}
123
+
124
+ Docs: ${docs}`;
125
+ }
126
+ });
127
+ export const scaffoldTools = [scaffoldTool];
File without changes
File without changes
File without changes
@@ -0,0 +1,53 @@
1
+ import { existsSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
3
+ export function resolveInsideRoot(root, relative) {
4
+ if (isAbsolute(relative)) return null;
5
+ const realRoot = existsSync(root) ? realpathSync(root) : resolve(root);
6
+ const target = resolve(realRoot, relative);
7
+ let existing = target;
8
+ while (!existsSync(existing) && dirname(existing) !== existing) {
9
+ existing = dirname(existing);
10
+ }
11
+ const realExisting = existsSync(existing) ? realpathSync(existing) : existing;
12
+ const rest = target.slice(existing.length);
13
+ const realTarget = join(realExisting, rest);
14
+ const boundary = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
15
+ return realTarget === realRoot || realTarget.startsWith(boundary) ? realTarget : null;
16
+ }
17
+ export function writeScaffold(files, { root, overwrite = false, allowed = true }) {
18
+ return files.map((file) => {
19
+ if (!allowed) {
20
+ return {
21
+ path: file.path,
22
+ status: "not-allowed",
23
+ reason: "writing is only available while the app runs in development"
24
+ };
25
+ }
26
+ if (isAbsolute(file.path)) {
27
+ return {
28
+ path: file.path,
29
+ status: "absolute-path",
30
+ reason: "paths must be relative to the project root"
31
+ };
32
+ }
33
+ const absolute = resolveInsideRoot(root, file.path);
34
+ if (!absolute) {
35
+ return {
36
+ path: file.path,
37
+ status: "outside-root",
38
+ reason: `resolves outside ${root}`
39
+ };
40
+ }
41
+ if (existsSync(absolute) && !overwrite) {
42
+ return {
43
+ path: file.path,
44
+ status: "exists",
45
+ absolute,
46
+ reason: "pass overwrite: true to replace it"
47
+ };
48
+ }
49
+ mkdirSync(dirname(absolute), { recursive: true });
50
+ writeFileSync(absolute, file.content, "utf-8");
51
+ return { path: file.path, status: "written", absolute };
52
+ });
53
+ }
@@ -0,0 +1,13 @@
1
+ import { defineMcpHandler } from "@nuxtjs/mcp-toolkit/server";
2
+ export default defineMcpHandler({
3
+ name: "mapo",
4
+ description: "Mapo admin framework: docs, component and field APIs, app introspection, scaffolding.",
5
+ instructions: `This server exposes the Mapo admin framework (Nuxt 4 + Nuxt UI) to coding agents.
6
+
7
+ Workflow:
8
+ 1. Call mapo_inspect_app before writing code for this project: it reports the mapo modules installed, the field types actually registered, the components available and the real configuration. mapo_doctor explains anything that looks misconfigured.
9
+ 2. Start from mapo_list_recipes to find the canonical approach for the task \u2014 Mapo ships a lot out of the box, and the recipe names the page that documents it.
10
+ 3. Use mapo_search_docs for anything the recipes do not cover, then mapo_get_doc to read the exact section. Prefer these over recalling Mapo APIs from memory: Mapo v2 differs substantially from v1.
11
+ 4. Never invent component props, slots or field types: look them up with mapo_component_api, mapo_list_field_types and mapo_composable_api, which read the installed source.
12
+ 5. Cite the doc path you relied on when you produce code.`
13
+ });
@@ -0,0 +1,3 @@
1
+ import { crudPagePrompt } from "../../../../core/prompts.js";
2
+ import { toMcpPrompt } from "../../../../nitro/to-mcp-prompt.js";
3
+ export default toMcpPrompt(crudPagePrompt);
@@ -0,0 +1,3 @@
1
+ import { customFieldPrompt } from "../../../../core/prompts.js";
2
+ import { toMcpPrompt } from "../../../../nitro/to-mcp-prompt.js";
3
+ export default toMcpPrompt(customFieldPrompt);
@@ -0,0 +1,3 @@
1
+ import { debugFormPrompt } from "../../../../core/prompts.js";
2
+ import { toMcpPrompt } from "../../../../nitro/to-mcp-prompt.js";
3
+ export default toMcpPrompt(debugFormPrompt);
@@ -0,0 +1,3 @@
1
+ import { migratePrompt } from "../../../../core/prompts.js";
2
+ import { toMcpPrompt } from "../../../../nitro/to-mcp-prompt.js";
3
+ export default toMcpPrompt(migratePrompt);
@@ -0,0 +1,3 @@
1
+ import { themePrompt } from "../../../../core/prompts.js";
2
+ import { toMcpPrompt } from "../../../../nitro/to-mcp-prompt.js";
3
+ export default toMcpPrompt(themePrompt);
@@ -0,0 +1,19 @@
1
+ import { defineMcpResource } from "@nuxtjs/mcp-toolkit/server";
2
+ import { MANIFEST_URI } from "../../../../core/resources.js";
3
+ import { useMapoManifest } from "../../../../nitro/context.js";
4
+ export default defineMcpResource({
5
+ name: "mapo-app-manifest",
6
+ title: "This app's Mapo setup",
7
+ description: "Installed Mapo modules, public Mapo config, registered field types, available components, admin routes and locales of the app currently running.",
8
+ uri: MANIFEST_URI,
9
+ metadata: { mimeType: "application/json" },
10
+ handler: (uri) => ({
11
+ contents: [
12
+ {
13
+ uri: uri.toString(),
14
+ mimeType: "application/json",
15
+ text: JSON.stringify(useMapoManifest(), null, 2)
16
+ }
17
+ ]
18
+ })
19
+ });
@@ -0,0 +1,34 @@
1
+ import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { defineMcpResource } from "@nuxtjs/mcp-toolkit/server";
3
+ import {
4
+ DOCS_URI_PREFIX,
5
+ docResourceList,
6
+ renderDocResource
7
+ } from "../../../../core/resources.js";
8
+ import { useDocsKnowledge } from "../../../../nitro/context.js";
9
+ export default defineMcpResource({
10
+ name: "mapo-doc",
11
+ title: "Mapo documentation page",
12
+ description: "A full Mapo documentation page, addressed by its path (e.g. howto/crud-list.md).",
13
+ uri: new ResourceTemplate(`${DOCS_URI_PREFIX}{+path}`, {
14
+ list: () => ({ resources: docResourceList(useDocsKnowledge()) })
15
+ }),
16
+ metadata: { mimeType: "text/markdown" },
17
+ handler: (uri, variables) => {
18
+ const raw = variables.path;
19
+ const path = Array.isArray(raw) ? raw.join("/") : raw ?? "";
20
+ const text = renderDocResource(
21
+ useDocsKnowledge(),
22
+ decodeURIComponent(path)
23
+ );
24
+ return {
25
+ contents: [
26
+ {
27
+ uri: uri.toString(),
28
+ mimeType: "text/markdown",
29
+ text: text ?? `No documentation page at "${path}".`
30
+ }
31
+ ]
32
+ };
33
+ }
34
+ });
@@ -0,0 +1,34 @@
1
+ import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { defineMcpResource } from "@nuxtjs/mcp-toolkit/server";
3
+ import {
4
+ FIELD_URI_PREFIX,
5
+ fieldResourceList,
6
+ renderFieldResource
7
+ } from "../../../../core/resources.js";
8
+ import { useApiKnowledge } from "../../../../nitro/context.js";
9
+ export default defineMcpResource({
10
+ name: "mapo-field-type",
11
+ title: "Mapo form field type",
12
+ description: "The full contract of a form field type: the component behind it, its attrs and the shared descriptor properties.",
13
+ uri: new ResourceTemplate(`${FIELD_URI_PREFIX}{type}`, {
14
+ list: () => ({ resources: fieldResourceList(useApiKnowledge()) })
15
+ }),
16
+ metadata: { mimeType: "text/markdown" },
17
+ handler: (uri, variables) => {
18
+ const raw = variables.type;
19
+ const type = Array.isArray(raw) ? raw[0] : raw ?? "";
20
+ const text = renderFieldResource(
21
+ useApiKnowledge(),
22
+ decodeURIComponent(type)
23
+ );
24
+ return {
25
+ contents: [
26
+ {
27
+ uri: uri.toString(),
28
+ mimeType: "text/markdown",
29
+ text: text ?? `No field type "${type}" is registered.`
30
+ }
31
+ ]
32
+ };
33
+ }
34
+ });
@@ -0,0 +1,22 @@
1
+ import { defineMcpResource } from "@nuxtjs/mcp-toolkit/server";
2
+ import { INDEX_URI, renderKnowledgeIndex } from "../../../../core/resources.js";
3
+ import {
4
+ useApiKnowledge,
5
+ useDocsKnowledge
6
+ } from "../../../../nitro/context.js";
7
+ export default defineMcpResource({
8
+ name: "mapo-knowledge-index",
9
+ title: "Mapo knowledge index",
10
+ description: "Everything the Mapo MCP server knows: recipes, documentation pages, components, field types and composables.",
11
+ uri: INDEX_URI,
12
+ metadata: { mimeType: "text/markdown" },
13
+ handler: (uri) => ({
14
+ contents: [
15
+ {
16
+ uri: uri.toString(),
17
+ mimeType: "text/markdown",
18
+ text: renderKnowledgeIndex(useDocsKnowledge(), useApiKnowledge())
19
+ }
20
+ ]
21
+ })
22
+ });
@@ -0,0 +1,3 @@
1
+ import { backendSchemaTool } from "../../../../core/tools/backend.js";
2
+ import { toMcpTool } from "../../../../nitro/to-mcp-tool.js";
3
+ export default toMcpTool(backendSchemaTool);
@@ -0,0 +1,3 @@
1
+ import { componentApiTool } from "../../../../core/tools/api.js";
2
+ import { toMcpTool } from "../../../../nitro/to-mcp-tool.js";
3
+ export default toMcpTool(componentApiTool);
@@ -0,0 +1,3 @@
1
+ import { composableApiTool } from "../../../../core/tools/api.js";
2
+ import { toMcpTool } from "../../../../nitro/to-mcp-tool.js";
3
+ export default toMcpTool(composableApiTool);
@@ -0,0 +1,3 @@
1
+ import { doctorTool } from "../../../../core/tools/app.js";
2
+ import { toMcpTool } from "../../../../nitro/to-mcp-tool.js";
3
+ export default toMcpTool(doctorTool);
@@ -0,0 +1,3 @@
1
+ import { getDocTool } from "../../../../core/tools/docs.js";
2
+ import { toMcpTool } from "../../../../nitro/to-mcp-tool.js";
3
+ export default toMcpTool(getDocTool);
@@ -0,0 +1,3 @@
1
+ import { inspectAppTool } from "../../../../core/tools/app.js";
2
+ import { toMcpTool } from "../../../../nitro/to-mcp-tool.js";
3
+ export default toMcpTool(inspectAppTool);