@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/dist/build.mjs ADDED
@@ -0,0 +1,351 @@
1
+ import { existsSync, readdirSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { buildDocsKnowledge } from '../dist/runtime/core/indexer.js';
4
+ import { API_KNOWLEDGE_VERSION } from '../dist/runtime/core/knowledge.js';
5
+ import { createChecker } from 'vue-component-meta';
6
+ import ts from 'typescript';
7
+ import { pathToFileURL } from 'node:url';
8
+
9
+ const COMPONENT_PACKAGES = [
10
+ { pkg: "@mapomodule/uikit", dir: "packages/@mapomodule/uikit" },
11
+ { pkg: "@mapomodule/form", dir: "packages/@mapomodule/form" }
12
+ ];
13
+ const MAX_TYPE_LENGTH$1 = 160;
14
+ function shortenType(type) {
15
+ const collapsed = type.replace(/\s+/g, " ").trim();
16
+ return collapsed.length > MAX_TYPE_LENGTH$1 ? `${collapsed.slice(0, MAX_TYPE_LENGTH$1)}\u2026` : collapsed;
17
+ }
18
+ function firstSentence(description) {
19
+ if (!description) return void 0;
20
+ const trimmed = description.replace(/\s+/g, " ").trim();
21
+ return trimmed || void 0;
22
+ }
23
+ function collectVueFiles(root) {
24
+ if (!existsSync(root)) return [];
25
+ const files = [];
26
+ const walk = (dir) => {
27
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
28
+ const full = join(dir, entry.name);
29
+ if (entry.isDirectory()) walk(full);
30
+ else if (entry.name.endsWith(".vue")) files.push(full);
31
+ }
32
+ };
33
+ walk(root);
34
+ return files.sort();
35
+ }
36
+ function toMembers(entries, withType = true) {
37
+ return (entries ?? []).map((entry) => ({
38
+ name: entry.name,
39
+ ...withType && entry.type ? { type: shortenType(entry.type) } : {},
40
+ ...entry.required !== void 0 ? { required: entry.required } : {},
41
+ ...entry.default !== void 0 && entry.default !== "undefined" ? { default: shortenType(String(entry.default)) } : {},
42
+ ...firstSentence(entry.description) ? { description: firstSentence(entry.description) } : {}
43
+ }));
44
+ }
45
+ function extractComponents(repoRoot, docsFor) {
46
+ const components = [];
47
+ for (const { pkg, dir } of COMPONENT_PACKAGES) {
48
+ const packageRoot = join(repoRoot, dir);
49
+ const tsconfig = join(packageRoot, "tsconfig.json");
50
+ const componentsRoot = join(packageRoot, "src", "runtime", "components");
51
+ const files = collectVueFiles(componentsRoot).filter(
52
+ (file) => /\/Mapo[A-Z][^/]*\.vue$/.test(file)
53
+ );
54
+ if (!files.length || !existsSync(tsconfig)) continue;
55
+ const checker = createChecker(tsconfig, {
56
+ forceUseTs: true,
57
+ printer: { newLine: 1 }
58
+ });
59
+ for (const file of files) {
60
+ const name = file.split("/").pop().replace(/\.vue$/, "");
61
+ try {
62
+ const meta = checker.getComponentMeta(file);
63
+ const props = meta.props.filter(
64
+ (prop) => !prop.global
65
+ );
66
+ components.push({
67
+ name,
68
+ pkg,
69
+ file: relative(repoRoot, file),
70
+ ...firstSentence(meta.description) ? { description: firstSentence(meta.description) } : {},
71
+ props: toMembers(props),
72
+ events: toMembers(meta.events),
73
+ slots: toMembers(meta.slots),
74
+ exposed: toMembers(meta.exposed),
75
+ docs: docsFor(name)
76
+ });
77
+ } catch (error) {
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ console.warn(`[mapo-mcp] skipped ${name}: ${message}`);
80
+ }
81
+ }
82
+ }
83
+ return components.sort((a, b) => a.name.localeCompare(b.name));
84
+ }
85
+
86
+ const PACKAGES_ROOT = "packages/@mapomodule";
87
+ const MAX_SIGNATURE_LENGTH = 220;
88
+ const ADD_IMPORT_ENTRY = /name:\s*"([A-Za-z_$][\w$]*)"[\s\S]{0,160}?from:[\s\S]{0,120}?"(\.[^"]+)"/g;
89
+ function shorten$1(value) {
90
+ const collapsed = value.replace(/\s+/g, " ").trim();
91
+ return collapsed.length > MAX_SIGNATURE_LENGTH ? `${collapsed.slice(0, MAX_SIGNATURE_LENGTH)}\u2026` : collapsed;
92
+ }
93
+ function collectCandidates(repoRoot) {
94
+ const packagesDir = join(repoRoot, PACKAGES_ROOT);
95
+ if (!existsSync(packagesDir)) return [];
96
+ const candidates = [];
97
+ for (const entry of readdirSync(packagesDir, { withFileTypes: true })) {
98
+ if (!entry.isDirectory()) continue;
99
+ const moduleFile = join(packagesDir, entry.name, "src", "module.ts");
100
+ if (!existsSync(moduleFile)) continue;
101
+ const source = readFileSync(moduleFile, "utf-8");
102
+ const packageRoot = join(packagesDir, entry.name);
103
+ for (const match of source.matchAll(ADD_IMPORT_ENTRY)) {
104
+ const [, name, from] = match;
105
+ if (!name || !from) continue;
106
+ const base = join(packageRoot, "src", from.replace(/^\.\//, ""));
107
+ const file = [".ts", ".mts", "/index.ts"].map((suffix) => `${base}${suffix}`).find((path) => existsSync(path));
108
+ if (file)
109
+ candidates.push({ name, pkg: `@mapomodule/${entry.name}`, file });
110
+ }
111
+ }
112
+ return candidates;
113
+ }
114
+ function extractComposables(repoRoot, docsFor) {
115
+ const candidates = collectCandidates(repoRoot);
116
+ if (!candidates.length) return [];
117
+ const program = ts.createProgram(
118
+ candidates.map((candidate) => candidate.file),
119
+ {
120
+ target: ts.ScriptTarget.ESNext,
121
+ module: ts.ModuleKind.ESNext,
122
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
123
+ strict: true,
124
+ noEmit: true,
125
+ skipLibCheck: true,
126
+ allowJs: true
127
+ }
128
+ );
129
+ const checker = program.getTypeChecker();
130
+ const composables = [];
131
+ for (const candidate of candidates) {
132
+ const source = program.getSourceFile(candidate.file);
133
+ const moduleSymbol = source ? checker.getSymbolAtLocation(source) : void 0;
134
+ const exported = moduleSymbol ? checker.getExportsOfModule(moduleSymbol).find((symbol) => symbol.getName() === candidate.name) : void 0;
135
+ const declaration = exported?.valueDeclaration ?? exported?.declarations?.[0];
136
+ const signature = exported && declaration ? checker.typeToString(
137
+ checker.getTypeOfSymbolAtLocation(exported, declaration)
138
+ ) : void 0;
139
+ const description = exported ? ts.displayPartsToString(exported.getDocumentationComment(checker)).trim() : "";
140
+ composables.push({
141
+ name: candidate.name,
142
+ pkg: candidate.pkg,
143
+ file: relative(repoRoot, candidate.file),
144
+ ...signature ? { signature: shorten$1(signature) } : {},
145
+ ...description ? { description: description.replace(/\s+/g, " ") } : {},
146
+ docs: docsFor(candidate.name)
147
+ });
148
+ }
149
+ return composables.sort((a, b) => a.name.localeCompare(b.name));
150
+ }
151
+
152
+ const FORM_PACKAGE = "packages/@mapomodule/form";
153
+ const DESCRIPTOR_FILE = "src/runtime/types/descriptor.ts";
154
+ const REGISTRY_FILE = "src/runtime/registry/defaults.ts";
155
+ const MAX_TYPE_LENGTH = 160;
156
+ function shorten(value) {
157
+ const collapsed = value.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").trim();
158
+ return collapsed.length > MAX_TYPE_LENGTH ? `${collapsed.slice(0, MAX_TYPE_LENGTH)}\u2026` : collapsed;
159
+ }
160
+ function docOf(symbol, checker) {
161
+ if (!symbol) return void 0;
162
+ const text = ts.displayPartsToString(symbol.getDocumentationComment(checker)).trim();
163
+ return text ? text.replace(/\s+/g, " ") : void 0;
164
+ }
165
+ function literalsOf(typeText) {
166
+ return [...typeText.matchAll(/"([^"]+)"/g)].map((match) => match[1]);
167
+ }
168
+ function membersOf(type, checker) {
169
+ return checker.getPropertiesOfType(type).map((property) => {
170
+ const declaration = property.valueDeclaration ?? property.declarations?.[0];
171
+ const declared = declaration && ts.isPropertySignature(declaration) && declaration.type ? declaration.type.getText() : void 0;
172
+ const resolved = declaration ? checker.typeToString(
173
+ checker.getTypeOfSymbolAtLocation(property, declaration)
174
+ ) : void 0;
175
+ const type_ = declared ?? resolved;
176
+ return {
177
+ name: property.getName(),
178
+ ...type_ ? { type: shorten(type_) } : {},
179
+ required: !(property.flags & ts.SymbolFlags.Optional),
180
+ ...docOf(property, checker) ? { description: docOf(property, checker) } : {}
181
+ };
182
+ });
183
+ }
184
+ function readDescriptors(descriptorPath) {
185
+ const program = ts.createProgram([descriptorPath], {
186
+ target: ts.ScriptTarget.ESNext,
187
+ module: ts.ModuleKind.ESNext,
188
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
189
+ strict: true,
190
+ noEmit: true,
191
+ skipLibCheck: true
192
+ });
193
+ const checker = program.getTypeChecker();
194
+ const source = program.getSourceFile(descriptorPath);
195
+ if (!source) return { descriptors: [], common: [] };
196
+ const descriptors = [];
197
+ let common = [];
198
+ for (const statement of source.statements) {
199
+ if (!ts.isInterfaceDeclaration(statement)) continue;
200
+ const name = statement.name.text;
201
+ const type = checker.getTypeAtLocation(statement.name);
202
+ if (name === "FieldBase") {
203
+ common = membersOf(type, checker).filter(
204
+ (member) => member.name !== "type"
205
+ );
206
+ continue;
207
+ }
208
+ const extendsFieldBase = statement.heritageClauses?.some(
209
+ (clause) => clause.types.some(
210
+ (heritage) => heritage.expression.getText(source) === "FieldBase"
211
+ )
212
+ );
213
+ if (!extendsFieldBase) continue;
214
+ const properties = checker.getPropertiesOfType(type);
215
+ const typeProperty = properties.find(
216
+ (property) => property.getName() === "type"
217
+ );
218
+ const attrsProperty = properties.find(
219
+ (property) => property.getName() === "attrs"
220
+ );
221
+ const typeDeclaration = typeProperty?.valueDeclaration ?? typeProperty?.declarations?.[0];
222
+ const typeText = typeDeclaration ? checker.typeToString(
223
+ checker.getTypeOfSymbolAtLocation(typeProperty, typeDeclaration)
224
+ ) : "";
225
+ const attrsDeclaration = attrsProperty?.valueDeclaration ?? attrsProperty?.declarations?.[0];
226
+ const attrs = attrsDeclaration ? membersOf(
227
+ checker.getNonNullableType(
228
+ checker.getTypeOfSymbolAtLocation(attrsProperty, attrsDeclaration)
229
+ ),
230
+ checker
231
+ ) : [];
232
+ descriptors.push({
233
+ interfaceName: name,
234
+ ...docOf(checker.getSymbolAtLocation(statement.name), checker) ? {
235
+ description: docOf(
236
+ checker.getSymbolAtLocation(statement.name),
237
+ checker
238
+ )
239
+ } : {},
240
+ types: literalsOf(typeText),
241
+ attrs
242
+ });
243
+ }
244
+ return { descriptors, common };
245
+ }
246
+ function componentNameOf(entry) {
247
+ if (typeof entry === "string") return entry;
248
+ if (typeof entry !== "function") return void 0;
249
+ const match = /([\w-]+)\.vue/.exec(String(entry));
250
+ return match?.[1];
251
+ }
252
+ async function extractFieldTypes(repoRoot, docsFor) {
253
+ const descriptorPath = join(repoRoot, FORM_PACKAGE, DESCRIPTOR_FILE);
254
+ const registryPath = join(repoRoot, FORM_PACKAGE, REGISTRY_FILE);
255
+ if (!existsSync(descriptorPath) || !existsSync(registryPath)) {
256
+ console.warn(
257
+ "[mapo-mcp] form package sources not found \u2014 skipping field extraction"
258
+ );
259
+ return { fieldTypes: [], fieldCommon: [] };
260
+ }
261
+ const { descriptors, common } = readDescriptors(descriptorPath);
262
+ const { createJiti } = await import('jiti');
263
+ const module_ = await createJiti(import.meta.url).import(
264
+ pathToFileURL(registryPath).href
265
+ );
266
+ const registry = module_.defaultRegistry;
267
+ const byType = /* @__PURE__ */ new Map();
268
+ for (const descriptor of descriptors) {
269
+ for (const type of descriptor.types) {
270
+ byType.set(type, {
271
+ type,
272
+ descriptor: descriptor.interfaceName,
273
+ ...descriptor.description ? { description: descriptor.description } : {},
274
+ attrs: descriptor.attrs,
275
+ docs: docsFor(type)
276
+ });
277
+ }
278
+ }
279
+ for (const type of Object.keys(registry.mapping ?? {})) {
280
+ if (!byType.has(type))
281
+ byType.set(type, { type, attrs: [], docs: docsFor(type) });
282
+ }
283
+ for (const [type, entry] of byType) {
284
+ const component = componentNameOf(registry.mapping?.[type]);
285
+ if (component) entry.component = component;
286
+ const defaults = {
287
+ ...registry.attrs?.All ?? {},
288
+ ...registry.attrs?.[type] ?? {}
289
+ };
290
+ if (Object.keys(defaults).length) entry.defaultAttrs = defaults;
291
+ if (registry.accessor?.[type]) entry.hasAccessor = true;
292
+ }
293
+ return {
294
+ fieldTypes: [...byType.values()].sort(
295
+ (a, b) => a.type.localeCompare(b.type)
296
+ ),
297
+ fieldCommon: common
298
+ };
299
+ }
300
+
301
+ const DOCS_FILE = "docs.json";
302
+ const API_FILE = "api.json";
303
+ const MAX_DOC_LINKS = 3;
304
+ function makeDocsResolver(knowledge) {
305
+ const chunks = knowledge.chunks;
306
+ return (symbol, pathPrefix) => {
307
+ const needle = symbol.toLowerCase();
308
+ const scored = [];
309
+ for (const chunk of chunks) {
310
+ if (pathPrefix && !chunk.path.startsWith(pathPrefix)) continue;
311
+ const heading = chunk.heading.toLowerCase();
312
+ const tags = chunk.tags.map((tag) => tag.toLowerCase());
313
+ let score = 0;
314
+ if (heading === needle || heading === `\`${needle}\``) score = 3;
315
+ else if (heading.includes(needle)) score = 2;
316
+ else if (tags.includes(needle)) score = 1;
317
+ if (score) scored.push({ chunk, score });
318
+ }
319
+ return scored.sort((a, b) => b.score - a.score).slice(0, MAX_DOC_LINKS).map(
320
+ ({ chunk }) => chunk.anchor ? `${chunk.path}#${chunk.anchor}` : chunk.path
321
+ );
322
+ };
323
+ }
324
+ async function buildKnowledge({
325
+ docsRoot,
326
+ repoRoot,
327
+ outDir
328
+ }) {
329
+ const docs = buildDocsKnowledge(docsRoot);
330
+ const docsFor = makeDocsResolver(docs);
331
+ const components = extractComponents(repoRoot, (name) => docsFor(name));
332
+ const { fieldTypes, fieldCommon } = await extractFieldTypes(
333
+ repoRoot,
334
+ (type) => docsFor(type, "uikit/form")
335
+ );
336
+ const composables = extractComposables(repoRoot, (name) => docsFor(name));
337
+ const api = {
338
+ version: API_KNOWLEDGE_VERSION,
339
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
340
+ components,
341
+ fieldTypes,
342
+ fieldCommon,
343
+ composables
344
+ };
345
+ mkdirSync(outDir, { recursive: true });
346
+ writeFileSync(join(outDir, DOCS_FILE), JSON.stringify(docs));
347
+ writeFileSync(join(outDir, API_FILE), JSON.stringify(api));
348
+ return { docs, api };
349
+ }
350
+
351
+ export { API_FILE, DOCS_FILE, buildKnowledge };
package/dist/cli.d.mts ADDED
@@ -0,0 +1,7 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+
3
+ /** Default endpoint of the Nuxt module, overridable with `--app`. */
4
+ declare const DEFAULT_APP_URL: string;
5
+ declare function createStdioServer(knowledgeDir: string | null, appUrl?: string, rootDir?: string, schemaUrl?: string | null): Promise<McpServer>;
6
+
7
+ export { DEFAULT_APP_URL, createStdioServer };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+
3
+ /** Default endpoint of the Nuxt module, overridable with `--app`. */
4
+ declare const DEFAULT_APP_URL: string;
5
+ declare function createStdioServer(knowledgeDir: string | null, appUrl?: string, rootDir?: string, schemaUrl?: string | null): Promise<McpServer>;
6
+
7
+ export { DEFAULT_APP_URL, createStdioServer };
package/dist/cli.mjs ADDED
@@ -0,0 +1,274 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
3
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
4
+ import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
+ import { defineCommand, runMain } from 'citty';
7
+ import { INDEX_URI, renderKnowledgeIndex, OVERVIEW_URI, DOCS_URI_PREFIX, docResourceList, renderDocResource, FIELD_URI_PREFIX, fieldResourceList, renderFieldResource } from '../dist/runtime/core/resources.js';
8
+ import { mcpEndpointUrl } from '../dist/runtime/core/endpoint.js';
9
+ import { MAPO_INSTRUCTIONS } from '../dist/runtime/core/instructions.js';
10
+ import { renderOverview } from '../dist/runtime/core/overview.js';
11
+ import { apiTools } from '../dist/runtime/core/tools/api.js';
12
+ import { appTools } from '../dist/runtime/core/tools/app.js';
13
+ import { docsTools } from '../dist/runtime/core/tools/docs.js';
14
+ import { scaffoldTools } from '../dist/runtime/core/tools/scaffold.js';
15
+ import { backendTools } from '../dist/runtime/core/tools/backend.js';
16
+ import { PROMPTS } from '../dist/runtime/core/prompts.js';
17
+ import { resolveKnowledgeDir, loadApiKnowledge, loadDocsKnowledge } from '../dist/runtime/core/knowledge.js';
18
+
19
+ function readVersion() {
20
+ try {
21
+ const pkg = JSON.parse(
22
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8")
23
+ );
24
+ return String(pkg.version ?? "0.0.0");
25
+ } catch {
26
+ return "0.0.0";
27
+ }
28
+ }
29
+ const DEFAULT_APP_URL = mcpEndpointUrl("http://localhost:3000");
30
+ function staticTools() {
31
+ return [...docsTools, ...apiTools, ...scaffoldTools, ...backendTools];
32
+ }
33
+ function createToolContext(knowledgeDir, rootDir, schemaUrl = null) {
34
+ let docs = null;
35
+ let api = null;
36
+ return {
37
+ knowledge: () => docs ??= loadDocsKnowledge(knowledgeDir),
38
+ api: () => api ??= loadApiKnowledge(knowledgeDir),
39
+ // The CLI has no app of its own; live tools are forwarded instead.
40
+ manifest: () => null,
41
+ // The editor spawns this process inside the project, so the working
42
+ // directory is the project — reported back on every write so a wrong root
43
+ // is visible immediately.
44
+ rootDir: () => rootDir,
45
+ canWrite: () => true,
46
+ // No nuxt.config to read: the CLI takes the schema from a flag or the env.
47
+ backend: () => ({
48
+ schemaUrl: schemaUrl ?? process.env.MAPO_BACKEND_SCHEMA_URL ?? null,
49
+ token: process.env.MAPO_BACKEND_TOKEN ?? null
50
+ })
51
+ };
52
+ }
53
+ function textOf(result) {
54
+ const content = result.content ?? [];
55
+ return content.filter((part) => part.type === "text" && part.text).map((part) => part.text).join("\n");
56
+ }
57
+ function createAppProxy(appUrl) {
58
+ let client = null;
59
+ return async function forward(name, args) {
60
+ try {
61
+ if (!client) {
62
+ const candidate = new Client({
63
+ name: "mapo-mcp-cli",
64
+ version: readVersion()
65
+ });
66
+ await candidate.connect(
67
+ new StreamableHTTPClientTransport(new URL(appUrl))
68
+ );
69
+ client = candidate;
70
+ }
71
+ return textOf(await client.callTool({ name, arguments: args }));
72
+ } catch (error) {
73
+ client = null;
74
+ const message = error instanceof Error ? error.message : String(error);
75
+ return `\`${name}\` needs the running app, and ${appUrl} is not answering (${message}).
76
+
77
+ Start the dev server (\`pnpm dev\`) and call the tool again. If the app runs on another port, behind a proxy or under an \`app.baseURL\`, pass its endpoint with \`--app\` or \`MAPO_MCP_APP_URL\` (for example \`http://localhost/backoffice/mcp/mapo\`): the dev server prints it at startup. Documentation and API tools work without it.`;
78
+ }
79
+ };
80
+ }
81
+ async function createStdioServer(knowledgeDir, appUrl = DEFAULT_APP_URL, rootDir = process.cwd(), schemaUrl = null) {
82
+ const server = new McpServer(
83
+ { name: "mapo", version: readVersion() },
84
+ { instructions: MAPO_INSTRUCTIONS }
85
+ );
86
+ const context = createToolContext(knowledgeDir, rootDir, schemaUrl);
87
+ for (const spec of staticTools()) {
88
+ server.registerTool(
89
+ spec.name,
90
+ {
91
+ title: spec.title,
92
+ description: spec.description,
93
+ inputSchema: spec.inputSchema,
94
+ ...spec.annotations ? { annotations: spec.annotations } : {}
95
+ },
96
+ async (args) => {
97
+ try {
98
+ const text = await spec.run(args, context);
99
+ return { content: [{ type: "text", text }] };
100
+ } catch (error) {
101
+ const message = error instanceof Error ? error.message : String(error);
102
+ return {
103
+ content: [{ type: "text", text: message }],
104
+ isError: true
105
+ };
106
+ }
107
+ }
108
+ );
109
+ }
110
+ const forward = createAppProxy(appUrl);
111
+ for (const spec of appTools) {
112
+ server.registerTool(
113
+ spec.name,
114
+ {
115
+ title: spec.title,
116
+ description: spec.description,
117
+ inputSchema: spec.inputSchema,
118
+ ...spec.annotations ? { annotations: spec.annotations } : {}
119
+ },
120
+ async (args) => ({
121
+ content: [
122
+ { type: "text", text: await forward(spec.name, args) }
123
+ ]
124
+ })
125
+ );
126
+ }
127
+ registerResources(server, context);
128
+ registerPrompts(server);
129
+ return server;
130
+ }
131
+ function registerPrompts(server) {
132
+ for (const prompt of PROMPTS) {
133
+ server.registerPrompt(
134
+ prompt.name,
135
+ {
136
+ title: prompt.title,
137
+ description: prompt.description,
138
+ argsSchema: prompt.argsSchema
139
+ },
140
+ // Same widening as the Nitro adapter: the SDK infers `unknown` from a
141
+ // generic shape, and zod has already validated the arguments.
142
+ (args) => ({
143
+ messages: [
144
+ {
145
+ role: "user",
146
+ content: {
147
+ type: "text",
148
+ text: prompt.render(args)
149
+ }
150
+ }
151
+ ]
152
+ })
153
+ );
154
+ }
155
+ }
156
+ function registerResources(server, context) {
157
+ const markdown = (uri, text) => ({
158
+ contents: [{ uri: uri.toString(), mimeType: "text/markdown", text }]
159
+ });
160
+ server.registerResource(
161
+ "mapo-knowledge-index",
162
+ INDEX_URI,
163
+ {
164
+ title: "Mapo knowledge index",
165
+ description: "Recipes, documentation pages, components, field types and composables known to this server.",
166
+ mimeType: "text/markdown"
167
+ },
168
+ (uri) => markdown(uri, renderKnowledgeIndex(context.knowledge(), context.api()))
169
+ );
170
+ server.registerResource(
171
+ "mapo-overview",
172
+ OVERVIEW_URI,
173
+ {
174
+ title: "Mapo overview",
175
+ description: "How Mapo fits together: the packages, the backend contract, declarative pages, the form engine and the customization layers.",
176
+ mimeType: "text/markdown"
177
+ },
178
+ (uri) => markdown(uri, renderOverview(context.knowledge()))
179
+ );
180
+ server.registerResource(
181
+ "mapo-doc",
182
+ new ResourceTemplate(`${DOCS_URI_PREFIX}{+path}`, {
183
+ list: () => ({ resources: docResourceList(context.knowledge()) })
184
+ }),
185
+ {
186
+ title: "Mapo documentation page",
187
+ description: "A full documentation page, addressed by its path.",
188
+ mimeType: "text/markdown"
189
+ },
190
+ (uri, variables) => {
191
+ const raw = variables.path;
192
+ const path = Array.isArray(raw) ? raw.join("/") : raw ?? "";
193
+ const text = renderDocResource(
194
+ context.knowledge(),
195
+ decodeURIComponent(path)
196
+ );
197
+ return markdown(uri, text ?? `No documentation page at "${path}".`);
198
+ }
199
+ );
200
+ server.registerResource(
201
+ "mapo-field-type",
202
+ new ResourceTemplate(`${FIELD_URI_PREFIX}{type}`, {
203
+ list: () => ({ resources: fieldResourceList(context.api()) })
204
+ }),
205
+ {
206
+ title: "Mapo form field type",
207
+ description: "The component, attrs and descriptor contract of a field type.",
208
+ mimeType: "text/markdown"
209
+ },
210
+ (uri, variables) => {
211
+ const raw = variables.type;
212
+ const type = Array.isArray(raw) ? raw[0] : raw ?? "";
213
+ const text = renderFieldResource(context.api(), decodeURIComponent(type));
214
+ return markdown(uri, text ?? `No field type "${type}" is registered.`);
215
+ }
216
+ );
217
+ }
218
+ const serve = defineCommand({
219
+ meta: {
220
+ name: "serve",
221
+ description: "Run the Mapo MCP server on stdio (for IDE/agent clients)"
222
+ },
223
+ args: {
224
+ knowledge: {
225
+ type: "string",
226
+ description: "Path to a prebuilt knowledge directory (defaults to the bundled one)"
227
+ },
228
+ app: {
229
+ type: "string",
230
+ description: `MCP endpoint of the running app, for the live tools (default ${DEFAULT_APP_URL})`
231
+ },
232
+ root: {
233
+ type: "string",
234
+ description: "Project root for scaffolding (default: the working directory)"
235
+ }
236
+ },
237
+ async run({ args }) {
238
+ const knowledgeDir = args.knowledge ? String(args.knowledge) : resolveKnowledgeDir();
239
+ if (!knowledgeDir) {
240
+ console.error(
241
+ "[mapo-mcp] knowledge base not found \u2014 docs tools will fail. Build it with `pnpm --filter @mapomodule/mcp build`."
242
+ );
243
+ }
244
+ const appUrl = String(
245
+ args.app ?? process.env.MAPO_MCP_APP_URL ?? DEFAULT_APP_URL
246
+ );
247
+ const rootDir = String(args.root ?? process.cwd());
248
+ const schemaUrl = args.schema ? String(args.schema) : null;
249
+ const server = await createStdioServer(
250
+ knowledgeDir,
251
+ appUrl,
252
+ rootDir,
253
+ schemaUrl
254
+ );
255
+ await server.connect(new StdioServerTransport());
256
+ console.error(
257
+ `[mapo-mcp] ready on stdio (${staticTools().length} tools, ${appTools.length} forwarded to ${appUrl})`
258
+ );
259
+ }
260
+ });
261
+ const main = defineCommand({
262
+ meta: {
263
+ name: "mapo-mcp",
264
+ version: readVersion(),
265
+ description: "Mapo MCP server and IDE integration helper"
266
+ },
267
+ subCommands: { serve },
268
+ // Bare `mapo-mcp` behaves like `mapo-mcp serve`: MCP clients spawn the bin
269
+ // with no arguments.
270
+ run: (context) => serve.run?.(context)
271
+ });
272
+ runMain(main);
273
+
274
+ export { DEFAULT_APP_URL, createStdioServer };