@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/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 = "http://localhost:3000/mcp/mapo";
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 = "http://localhost:3000/mcp/mapo";
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,263 @@
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, DOCS_URI_PREFIX, docResourceList, renderDocResource, FIELD_URI_PREFIX, fieldResourceList, renderFieldResource } from '../dist/runtime/core/resources.js';
8
+ import { apiTools } from '../dist/runtime/core/tools/api.js';
9
+ import { appTools } from '../dist/runtime/core/tools/app.js';
10
+ import { docsTools } from '../dist/runtime/core/tools/docs.js';
11
+ import { scaffoldTools } from '../dist/runtime/core/tools/scaffold.js';
12
+ import { backendTools } from '../dist/runtime/core/tools/backend.js';
13
+ import { PROMPTS } from '../dist/runtime/core/prompts.js';
14
+ import { resolveKnowledgeDir, loadApiKnowledge, loadDocsKnowledge } from '../dist/runtime/core/knowledge.js';
15
+
16
+ function readVersion() {
17
+ try {
18
+ const pkg = JSON.parse(
19
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8")
20
+ );
21
+ return String(pkg.version ?? "0.0.0");
22
+ } catch {
23
+ return "0.0.0";
24
+ }
25
+ }
26
+ const DEFAULT_APP_URL = "http://localhost:3000/mcp/mapo";
27
+ function staticTools() {
28
+ return [...docsTools, ...apiTools, ...scaffoldTools, ...backendTools];
29
+ }
30
+ function createToolContext(knowledgeDir, rootDir, schemaUrl = null) {
31
+ let docs = null;
32
+ let api = null;
33
+ return {
34
+ knowledge: () => docs ??= loadDocsKnowledge(knowledgeDir),
35
+ api: () => api ??= loadApiKnowledge(knowledgeDir),
36
+ // The CLI has no app of its own; live tools are forwarded instead.
37
+ manifest: () => null,
38
+ // The editor spawns this process inside the project, so the working
39
+ // directory is the project — reported back on every write so a wrong root
40
+ // is visible immediately.
41
+ rootDir: () => rootDir,
42
+ canWrite: () => true,
43
+ // No nuxt.config to read: the CLI takes the schema from a flag or the env.
44
+ backend: () => ({
45
+ schemaUrl: schemaUrl ?? process.env.MAPO_BACKEND_SCHEMA_URL ?? null,
46
+ token: process.env.MAPO_BACKEND_TOKEN ?? null
47
+ })
48
+ };
49
+ }
50
+ function textOf(result) {
51
+ const content = result.content ?? [];
52
+ return content.filter((part) => part.type === "text" && part.text).map((part) => part.text).join("\n");
53
+ }
54
+ function createAppProxy(appUrl) {
55
+ let client = null;
56
+ return async function forward(name, args) {
57
+ try {
58
+ if (!client) {
59
+ const candidate = new Client({
60
+ name: "mapo-mcp-cli",
61
+ version: readVersion()
62
+ });
63
+ await candidate.connect(
64
+ new StreamableHTTPClientTransport(new URL(appUrl))
65
+ );
66
+ client = candidate;
67
+ }
68
+ return textOf(await client.callTool({ name, arguments: args }));
69
+ } catch (error) {
70
+ client = null;
71
+ const message = error instanceof Error ? error.message : String(error);
72
+ return `\`${name}\` needs the running app, and ${appUrl} is not answering (${message}).
73
+
74
+ Start the dev server (\`pnpm dev\`) and call the tool again, or point the client directly at the app endpoint. Documentation and API tools work without it.`;
75
+ }
76
+ };
77
+ }
78
+ async function createStdioServer(knowledgeDir, appUrl = DEFAULT_APP_URL, rootDir = process.cwd(), schemaUrl = null) {
79
+ const server = new McpServer(
80
+ { name: "mapo", version: readVersion() },
81
+ {
82
+ instructions: "Mapo admin framework (Nuxt 4). Start from mapo_list_recipes, then mapo_search_docs / mapo_get_doc for how-to, and mapo_component_api / mapo_list_field_types / mapo_composable_api for exact APIs \u2014 Mapo v2 differs substantially from v1, so never recall its API from memory. mapo_inspect_app and mapo_doctor describe the project itself and need its dev server running."
83
+ }
84
+ );
85
+ const context = createToolContext(knowledgeDir, rootDir, schemaUrl);
86
+ for (const spec of staticTools()) {
87
+ server.registerTool(
88
+ spec.name,
89
+ {
90
+ title: spec.title,
91
+ description: spec.description,
92
+ inputSchema: spec.inputSchema,
93
+ ...spec.annotations ? { annotations: spec.annotations } : {}
94
+ },
95
+ async (args) => {
96
+ try {
97
+ const text = await spec.run(args, context);
98
+ return { content: [{ type: "text", text }] };
99
+ } catch (error) {
100
+ const message = error instanceof Error ? error.message : String(error);
101
+ return {
102
+ content: [{ type: "text", text: message }],
103
+ isError: true
104
+ };
105
+ }
106
+ }
107
+ );
108
+ }
109
+ const forward = createAppProxy(appUrl);
110
+ for (const spec of appTools) {
111
+ server.registerTool(
112
+ spec.name,
113
+ {
114
+ title: spec.title,
115
+ description: spec.description,
116
+ inputSchema: spec.inputSchema,
117
+ ...spec.annotations ? { annotations: spec.annotations } : {}
118
+ },
119
+ async (args) => ({
120
+ content: [
121
+ { type: "text", text: await forward(spec.name, args) }
122
+ ]
123
+ })
124
+ );
125
+ }
126
+ registerResources(server, context);
127
+ registerPrompts(server);
128
+ return server;
129
+ }
130
+ function registerPrompts(server) {
131
+ for (const prompt of PROMPTS) {
132
+ server.registerPrompt(
133
+ prompt.name,
134
+ {
135
+ title: prompt.title,
136
+ description: prompt.description,
137
+ argsSchema: prompt.argsSchema
138
+ },
139
+ // Same widening as the Nitro adapter: the SDK infers `unknown` from a
140
+ // generic shape, and zod has already validated the arguments.
141
+ (args) => ({
142
+ messages: [
143
+ {
144
+ role: "user",
145
+ content: {
146
+ type: "text",
147
+ text: prompt.render(args)
148
+ }
149
+ }
150
+ ]
151
+ })
152
+ );
153
+ }
154
+ }
155
+ function registerResources(server, context) {
156
+ const markdown = (uri, text) => ({
157
+ contents: [{ uri: uri.toString(), mimeType: "text/markdown", text }]
158
+ });
159
+ server.registerResource(
160
+ "mapo-knowledge-index",
161
+ INDEX_URI,
162
+ {
163
+ title: "Mapo knowledge index",
164
+ description: "Recipes, documentation pages, components, field types and composables known to this server.",
165
+ mimeType: "text/markdown"
166
+ },
167
+ (uri) => markdown(uri, renderKnowledgeIndex(context.knowledge(), context.api()))
168
+ );
169
+ server.registerResource(
170
+ "mapo-doc",
171
+ new ResourceTemplate(`${DOCS_URI_PREFIX}{+path}`, {
172
+ list: () => ({ resources: docResourceList(context.knowledge()) })
173
+ }),
174
+ {
175
+ title: "Mapo documentation page",
176
+ description: "A full documentation page, addressed by its path.",
177
+ mimeType: "text/markdown"
178
+ },
179
+ (uri, variables) => {
180
+ const raw = variables.path;
181
+ const path = Array.isArray(raw) ? raw.join("/") : raw ?? "";
182
+ const text = renderDocResource(
183
+ context.knowledge(),
184
+ decodeURIComponent(path)
185
+ );
186
+ return markdown(uri, text ?? `No documentation page at "${path}".`);
187
+ }
188
+ );
189
+ server.registerResource(
190
+ "mapo-field-type",
191
+ new ResourceTemplate(`${FIELD_URI_PREFIX}{type}`, {
192
+ list: () => ({ resources: fieldResourceList(context.api()) })
193
+ }),
194
+ {
195
+ title: "Mapo form field type",
196
+ description: "The component, attrs and descriptor contract of a field type.",
197
+ mimeType: "text/markdown"
198
+ },
199
+ (uri, variables) => {
200
+ const raw = variables.type;
201
+ const type = Array.isArray(raw) ? raw[0] : raw ?? "";
202
+ const text = renderFieldResource(context.api(), decodeURIComponent(type));
203
+ return markdown(uri, text ?? `No field type "${type}" is registered.`);
204
+ }
205
+ );
206
+ }
207
+ const serve = defineCommand({
208
+ meta: {
209
+ name: "serve",
210
+ description: "Run the Mapo MCP server on stdio (for IDE/agent clients)"
211
+ },
212
+ args: {
213
+ knowledge: {
214
+ type: "string",
215
+ description: "Path to a prebuilt knowledge directory (defaults to the bundled one)"
216
+ },
217
+ app: {
218
+ type: "string",
219
+ description: `MCP endpoint of the running app, for the live tools (default ${DEFAULT_APP_URL})`
220
+ },
221
+ root: {
222
+ type: "string",
223
+ description: "Project root for scaffolding (default: the working directory)"
224
+ }
225
+ },
226
+ async run({ args }) {
227
+ const knowledgeDir = args.knowledge ? String(args.knowledge) : resolveKnowledgeDir();
228
+ if (!knowledgeDir) {
229
+ console.error(
230
+ "[mapo-mcp] knowledge base not found \u2014 docs tools will fail. Build it with `pnpm --filter @mapomodule/mcp build`."
231
+ );
232
+ }
233
+ const appUrl = String(
234
+ args.app ?? process.env.MAPO_MCP_APP_URL ?? DEFAULT_APP_URL
235
+ );
236
+ const rootDir = String(args.root ?? process.cwd());
237
+ const schemaUrl = args.schema ? String(args.schema) : null;
238
+ const server = await createStdioServer(
239
+ knowledgeDir,
240
+ appUrl,
241
+ rootDir,
242
+ schemaUrl
243
+ );
244
+ await server.connect(new StdioServerTransport());
245
+ console.error(
246
+ `[mapo-mcp] ready on stdio (${staticTools().length} tools, ${appTools.length} forwarded to ${appUrl})`
247
+ );
248
+ }
249
+ });
250
+ const main = defineCommand({
251
+ meta: {
252
+ name: "mapo-mcp",
253
+ version: readVersion(),
254
+ description: "Mapo MCP server and IDE integration helper"
255
+ },
256
+ subCommands: { serve },
257
+ // Bare `mapo-mcp` behaves like `mapo-mcp serve`: MCP clients spawn the bin
258
+ // with no arguments.
259
+ run: (context) => serve.run?.(context)
260
+ });
261
+ runMain(main);
262
+
263
+ export { DEFAULT_APP_URL, createStdioServer };
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Public types for `@mapomodule/mcp`.
3
+ * Import from `@mapomodule/mcp/types`.
4
+ */
5
+ interface MapoMcpBackendOptions {
6
+ /**
7
+ * OpenAPI/DRF schema URL used by `mapo_backend_schema`
8
+ * (e.g. `http://localhost:8000/api/schema/?format=json`).
9
+ * Falls back to `MAPO_BACKEND_SCHEMA_URL`.
10
+ */
11
+ schemaUrl?: string;
12
+ /**
13
+ * Name of the environment variable holding the bearer token for the schema
14
+ * request. The value is never echoed back to the MCP client.
15
+ * @default "MAPO_BACKEND_TOKEN"
16
+ */
17
+ tokenEnv?: string;
18
+ }
19
+ interface MapoMcpOptions {
20
+ /**
21
+ * Register the MCP server. Defaults to `nuxt.options.dev` — the server is a
22
+ * development tool and never ships in a production build unless forced.
23
+ */
24
+ enabled?: boolean;
25
+ backend?: MapoMcpBackendOptions;
26
+ }
27
+ /** Field type registered in the form registry, as seen at build time. */
28
+ interface MapoManifestFieldType {
29
+ type: string;
30
+ source: "default" | "config";
31
+ }
32
+ /** Build-time snapshot of the consuming app, exposed by `mapo_inspect_app`. */
33
+ interface MapoAppManifest {
34
+ /** Absolute path of the app root (dev machine). */
35
+ rootDir: string;
36
+ dev: boolean;
37
+ /** Installed `@mapomodule/*` modules and their versions. */
38
+ modules: Array<{
39
+ name: string;
40
+ version?: string;
41
+ }>;
42
+ /**
43
+ * `modules[]` as written in `nuxt.config`, in order. Only string entries are
44
+ * reported — inline function modules have no stable name. Ordering matters:
45
+ * `@nuxt/ui` must come before `mapomodule`.
46
+ */
47
+ moduleOrder: string[];
48
+ /** Public Mapo runtime config; secret values are replaced by their key names. */
49
+ config: Record<string, unknown>;
50
+ fieldTypes: MapoManifestFieldType[];
51
+ components: string[];
52
+ routes: Array<{
53
+ path: string;
54
+ file?: string;
55
+ }>;
56
+ locales: string[];
57
+ }
58
+ /** Payload of the `#mapo-mcp/context.mjs` virtual server module. */
59
+ interface MapoMcpContext {
60
+ /** Absolute path of the generated knowledge base, or `null` when not built. */
61
+ knowledgeDir: string | null;
62
+ backend: Required<Pick<MapoMcpBackendOptions, "tokenEnv">> & {
63
+ schemaUrl: string | null;
64
+ };
65
+ manifest: MapoAppManifest;
66
+ }
67
+
68
+ export type { MapoAppManifest, MapoManifestFieldType, MapoMcpBackendOptions, MapoMcpContext, MapoMcpOptions };