@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,417 @@
1
+ /**
2
+ * OpenAPI / DRF schema → Mapo field descriptors.
3
+ *
4
+ * Django REST Framework projects already describe every serializer in their
5
+ * OpenAPI document (drf-spectacular). That document knows the types, the
6
+ * choices, the read-only flags and the length limits — everything a form needs
7
+ * and everything a model would otherwise guess.
8
+ *
9
+ * Pure and dependency-free: fetching happens elsewhere, so the mapping is
10
+ * testable against fixtures.
11
+ */
12
+
13
+ /** Minimal shape we rely on; the rest of the document is ignored. */
14
+ export interface OpenApiDocument {
15
+ openapi?: string;
16
+ info?: { title?: string; version?: string };
17
+ paths?: Record<string, Record<string, unknown>>;
18
+ components?: { schemas?: Record<string, OpenApiSchema> };
19
+ }
20
+
21
+ export interface OpenApiSchema {
22
+ type?: string;
23
+ format?: string;
24
+ title?: string;
25
+ description?: string;
26
+ enum?: unknown[];
27
+ properties?: Record<string, OpenApiSchema>;
28
+ required?: string[];
29
+ items?: OpenApiSchema;
30
+ readOnly?: boolean;
31
+ writeOnly?: boolean;
32
+ nullable?: boolean;
33
+ maxLength?: number;
34
+ minLength?: number;
35
+ maximum?: number;
36
+ minimum?: number;
37
+ $ref?: string;
38
+ allOf?: OpenApiSchema[];
39
+ oneOf?: OpenApiSchema[];
40
+ [key: string]: unknown;
41
+ }
42
+
43
+ export interface MappedField {
44
+ key: string;
45
+ type: string;
46
+ label: string;
47
+ required?: boolean;
48
+ readonly?: boolean;
49
+ attrs?: Record<string, unknown>;
50
+ /** Why this mapping is uncertain, when it is. */
51
+ note?: string;
52
+ }
53
+
54
+ export interface ModelSummary {
55
+ name: string;
56
+ title?: string;
57
+ description?: string;
58
+ /** List endpoint serving this model, when the document declares one. */
59
+ endpoint?: string;
60
+ fieldCount: number;
61
+ }
62
+
63
+ /** `#/components/schemas/Article` → `Article` */
64
+ function refName(ref: string): string {
65
+ return ref.split("/").pop() ?? ref;
66
+ }
67
+
68
+ /**
69
+ * Resolves `$ref` and the `allOf: [$ref]` wrapper drf-spectacular emits for
70
+ * nullable nested serializers, returning the schema plus the component name it
71
+ * came from (needed to look up the relation's endpoint).
72
+ */
73
+ export function resolveSchema(
74
+ doc: OpenApiDocument,
75
+ schema: OpenApiSchema | undefined,
76
+ depth = 0,
77
+ ): { schema: OpenApiSchema; ref?: string } {
78
+ if (!schema || depth > 5) return { schema: schema ?? {} };
79
+
80
+ if (schema.$ref) {
81
+ const name = refName(schema.$ref);
82
+ const target = doc.components?.schemas?.[name];
83
+ if (!target) return { schema: {}, ref: name };
84
+ const resolved = resolveSchema(doc, target, depth + 1);
85
+ return { schema: resolved.schema, ref: resolved.ref ?? name };
86
+ }
87
+
88
+ // `allOf` is a wrapper: merge the members, then let sibling keywords
89
+ // (`readOnly`, `nullable`, `title`) declared next to it win.
90
+ if (schema.allOf?.length) {
91
+ const merged = schema.allOf.reduce<{ schema: OpenApiSchema; ref?: string }>(
92
+ (accumulator, member) => {
93
+ const resolved = resolveSchema(doc, member, depth + 1);
94
+ return {
95
+ schema: { ...accumulator.schema, ...resolved.schema },
96
+ ref: resolved.ref ?? accumulator.ref,
97
+ };
98
+ },
99
+ { schema: {} },
100
+ );
101
+ const { allOf: _allOf, ...siblings } = schema;
102
+ return { schema: { ...merged.schema, ...siblings }, ref: merged.ref };
103
+ }
104
+
105
+ return { schema };
106
+ }
107
+
108
+ /**
109
+ * Maps every component to the collection endpoint that serves it, by reading
110
+ * the 200 response of each `get`. Both a bare `$ref` and DRF's paginated
111
+ * `{ count, results: [...] }` wrapper are recognised.
112
+ */
113
+ export function endpointsByModel(doc: OpenApiDocument): Map<string, string> {
114
+ const byModel = new Map<string, string>();
115
+
116
+ for (const [path, operations] of Object.entries(doc.paths ?? {})) {
117
+ // Collection endpoints only: `/api/articles/`, not `/api/articles/{id}/`.
118
+ if (/\{[^}]+\}/.test(path)) continue;
119
+
120
+ // Only the shape we read is described: the rest of an operation object is
121
+ // irrelevant here and typing it fully would be noise.
122
+ const get = (
123
+ operations as {
124
+ get?: {
125
+ responses?: Record<
126
+ string,
127
+ { content?: Record<string, { schema?: OpenApiSchema }> }
128
+ >;
129
+ };
130
+ }
131
+ )?.get;
132
+ const schema =
133
+ get?.responses?.["200"]?.content?.["application/json"]?.schema;
134
+ if (!schema) continue;
135
+
136
+ const direct = schema.$ref ? refName(schema.$ref) : undefined;
137
+ const results = schema.properties?.results;
138
+ const paginated = results?.items?.$ref
139
+ ? refName(results.items.$ref)
140
+ : undefined;
141
+ const array = schema.items?.$ref ? refName(schema.items.$ref) : undefined;
142
+
143
+ const model = paginated ?? array ?? direct;
144
+ if (model && !byModel.has(model)) byModel.set(model, path);
145
+ }
146
+
147
+ return byModel;
148
+ }
149
+
150
+ /** `published_at` → `Published at`; a `title` from the schema wins. */
151
+ function labelFor(key: string, schema: OpenApiSchema): string {
152
+ if (schema.title) return schema.title;
153
+ return key
154
+ .replace(/[_-]+/g, " ")
155
+ .trim()
156
+ .toLowerCase()
157
+ .replace(/^./, (character) => character.toUpperCase());
158
+ }
159
+
160
+ /** Long free text deserves a textarea rather than a single-line input. */
161
+ const TEXTAREA_THRESHOLD = 500;
162
+
163
+ function enumItems(
164
+ schema: OpenApiSchema,
165
+ ): Array<{ label: string; value: unknown }> {
166
+ return (schema.enum ?? []).map((value) => ({
167
+ label: String(value)
168
+ .replace(/[_-]+/g, " ")
169
+ .replace(/^./, (character) => character.toUpperCase()),
170
+ value,
171
+ }));
172
+ }
173
+
174
+ /**
175
+ * The mapping itself. Returns `null` when nothing sensible exists, so the
176
+ * caller can report the property instead of inventing a field for it.
177
+ */
178
+ export function mapProperty(
179
+ doc: OpenApiDocument,
180
+ key: string,
181
+ raw: OpenApiSchema,
182
+ options: { required?: boolean; endpoints?: Map<string, string> } = {},
183
+ ): MappedField | null {
184
+ const { schema, ref } = resolveSchema(doc, raw);
185
+ const endpoints = options.endpoints ?? new Map<string, string>();
186
+ const base: MappedField = {
187
+ key,
188
+ type: "text",
189
+ label: labelFor(key, schema),
190
+ ...(options.required ? { required: true } : {}),
191
+ ...(schema.readOnly ? { readonly: true } : {}),
192
+ };
193
+
194
+ // Choices come first: an enum is a select whatever its underlying type is.
195
+ if (schema.enum?.length) {
196
+ return { ...base, type: "select", attrs: { items: enumItems(schema) } };
197
+ }
198
+
199
+ if (schema.type === "boolean") return { ...base, type: "boolean" };
200
+
201
+ if (schema.type === "integer" || schema.type === "number") {
202
+ const attrs: Record<string, unknown> = {};
203
+ if (schema.minimum !== undefined) attrs.min = schema.minimum;
204
+ if (schema.maximum !== undefined) attrs.max = schema.maximum;
205
+ return {
206
+ ...base,
207
+ type: "number",
208
+ ...(Object.keys(attrs).length ? { attrs } : {}),
209
+ };
210
+ }
211
+
212
+ if (schema.type === "array") {
213
+ const item = resolveSchema(doc, schema.items);
214
+ // A list of related objects is a many-to-many picker, and the endpoint is
215
+ // inferable from the paths section.
216
+ if (item.ref) {
217
+ const endpoint = endpoints.get(item.ref);
218
+ return {
219
+ ...base,
220
+ type: "m2m",
221
+ attrs: {
222
+ endpoint: endpoint ?? `/api/${item.ref.toLowerCase()}/`,
223
+ itemValue: "id",
224
+ },
225
+ ...(endpoint
226
+ ? {}
227
+ : {
228
+ note: `no list endpoint found for ${item.ref}; check attrs.endpoint`,
229
+ }),
230
+ };
231
+ }
232
+ if (item.schema.enum?.length) {
233
+ return {
234
+ ...base,
235
+ type: "select",
236
+ attrs: { multiple: true, items: enumItems(item.schema) },
237
+ };
238
+ }
239
+ return {
240
+ ...base,
241
+ type: "repeater",
242
+ note: "array of plain values: a repeater expects objects, so review this one",
243
+ };
244
+ }
245
+
246
+ // A nested object with a component behind it is a foreign key.
247
+ if (ref && (schema.type === "object" || schema.properties)) {
248
+ const endpoint = endpoints.get(ref);
249
+ return {
250
+ ...base,
251
+ type: "fks",
252
+ attrs: {
253
+ endpoint: endpoint ?? `/api/${ref.toLowerCase()}/`,
254
+ itemValue: "id",
255
+ },
256
+ ...(endpoint
257
+ ? {}
258
+ : { note: `no list endpoint found for ${ref}; check attrs.endpoint` }),
259
+ };
260
+ }
261
+
262
+ if (schema.type === "object") {
263
+ return {
264
+ ...base,
265
+ type: "text",
266
+ note: "free-form object: consider a repeater or a custom field",
267
+ };
268
+ }
269
+
270
+ // Strings: the format carries most of the meaning.
271
+ switch (schema.format) {
272
+ case "date-time":
273
+ return { ...base, type: "datetime" };
274
+ case "date":
275
+ return { ...base, type: "date" };
276
+ case "time":
277
+ return { ...base, type: "time" };
278
+ case "email":
279
+ return { ...base, type: "email" };
280
+ case "uri":
281
+ case "url":
282
+ return { ...base, type: "url" };
283
+ case "binary":
284
+ return { ...base, type: "file" };
285
+ default:
286
+ break;
287
+ }
288
+
289
+ const attrs: Record<string, unknown> = {};
290
+ if (schema.maxLength !== undefined) attrs.maxLength = schema.maxLength;
291
+
292
+ const long =
293
+ schema.maxLength === undefined || schema.maxLength >= TEXTAREA_THRESHOLD;
294
+ return {
295
+ ...base,
296
+ type: long ? "textarea" : "text",
297
+ ...(Object.keys(attrs).length ? { attrs } : {}),
298
+ };
299
+ }
300
+
301
+ export interface ToFieldsOptions {
302
+ /** Keep server-computed fields (id, timestamps) as readonly descriptors. */
303
+ includeReadOnly?: boolean;
304
+ /** Restrict to the field types actually registered in the app. */
305
+ knownTypes?: Set<string>;
306
+ }
307
+
308
+ export interface ToFieldsResult {
309
+ model: string;
310
+ endpoint?: string;
311
+ fields: MappedField[];
312
+ /** Properties deliberately left out, with the reason. */
313
+ skipped: Array<{ key: string; reason: string }>;
314
+ notes: string[];
315
+ }
316
+
317
+ /** Every component schema of the document, with its endpoint when known. */
318
+ export function listModels(doc: OpenApiDocument): ModelSummary[] {
319
+ const endpoints = endpointsByModel(doc);
320
+
321
+ return Object.entries(doc.components?.schemas ?? {})
322
+ .map(([name, schema]) => ({
323
+ name,
324
+ ...(schema.title ? { title: schema.title } : {}),
325
+ ...(schema.description ? { description: schema.description } : {}),
326
+ ...(endpoints.has(name) ? { endpoint: endpoints.get(name)! } : {}),
327
+ fieldCount: Object.keys(schema.properties ?? {}).length,
328
+ }))
329
+ .sort((a, b) => a.name.localeCompare(b.name));
330
+ }
331
+
332
+ /** Maps one component into descriptors. */
333
+ export function toFields(
334
+ doc: OpenApiDocument,
335
+ model: string,
336
+ options: ToFieldsOptions = {},
337
+ ): ToFieldsResult | null {
338
+ const schema = doc.components?.schemas?.[model];
339
+ if (!schema) return null;
340
+
341
+ const endpoints = endpointsByModel(doc);
342
+ const required = new Set(schema.required ?? []);
343
+ const fields: MappedField[] = [];
344
+ const skipped: Array<{ key: string; reason: string }> = [];
345
+ const notes: string[] = [];
346
+
347
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
348
+ const { schema: resolved } = resolveSchema(doc, property);
349
+
350
+ if (resolved.readOnly && !options.includeReadOnly) {
351
+ skipped.push({ key, reason: "read-only in the API" });
352
+ continue;
353
+ }
354
+
355
+ const mapped = mapProperty(doc, key, property, {
356
+ required: required.has(key),
357
+ endpoints,
358
+ });
359
+
360
+ if (!mapped) {
361
+ skipped.push({ key, reason: "no sensible field type" });
362
+ continue;
363
+ }
364
+
365
+ // The app decides which types exist: never emit one it cannot render.
366
+ if (options.knownTypes && !options.knownTypes.has(mapped.type)) {
367
+ skipped.push({
368
+ key,
369
+ reason: `maps to \`${mapped.type}\`, which this app does not register`,
370
+ });
371
+ continue;
372
+ }
373
+
374
+ fields.push(mapped);
375
+ }
376
+
377
+ if (skipped.some((entry) => entry.reason === "read-only in the API")) {
378
+ notes.push(
379
+ "Read-only properties were skipped; pass includeReadOnly to keep them as readonly fields.",
380
+ );
381
+ }
382
+
383
+ return {
384
+ model,
385
+ ...(endpoints.has(model) ? { endpoint: endpoints.get(model)! } : {}),
386
+ fields,
387
+ skipped,
388
+ notes,
389
+ };
390
+ }
391
+
392
+ /** Renders the descriptors as the TypeScript a page would contain. */
393
+ export function renderFields(result: ToFieldsResult): string {
394
+ const body = result.fields
395
+ .map((field) => {
396
+ const parts = [
397
+ `key: "${field.key}"`,
398
+ `type: "${field.type}"`,
399
+ `label: "${field.label}"`,
400
+ ];
401
+ if (field.required) parts.push("required: true");
402
+ if (field.readonly) parts.push("readonly: true");
403
+ if (field.attrs) parts.push(`attrs: ${JSON.stringify(field.attrs)}`);
404
+ const comment = field.note ? ` // ${field.note}` : "";
405
+ return ` { ${parts.join(", ")} },${comment}`;
406
+ })
407
+ .join("\n");
408
+
409
+ return `const fields: FieldDescriptor<${result.model}>[] = [\n${body}\n];`;
410
+ }
411
+
412
+ /** `key:type:Label` specs, ready to hand to `mapo_scaffold`. */
413
+ export function toScaffoldSpecs(result: ToFieldsResult): string[] {
414
+ return result.fields.map(
415
+ (field) => `${field.key}:${field.type}:${field.label}`,
416
+ );
417
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * MCP prompts: the workflows, exposed as slash-commands in the IDE.
3
+ *
4
+ * A prompt is not documentation — it is an instruction the model receives as if
5
+ * the user had typed it. So each one names the exact tools to call and the
6
+ * order, which is the part a model gets wrong when left to improvise.
7
+ *
8
+ * Every tool named here must exist: a prompt that references a missing tool
9
+ * wastes a turn and teaches the model to distrust the server.
10
+ */
11
+ import { z } from "zod";
12
+ import type { ZodRawShape } from "zod";
13
+
14
+ export interface MapoPrompt<Args = Record<string, string | undefined>> {
15
+ name: string;
16
+ title: string;
17
+ description: string;
18
+ argsSchema: ZodRawShape;
19
+ /** The user-role message handed to the model. */
20
+ render: (args: Args) => string;
21
+ }
22
+
23
+ const optional = (description: string) =>
24
+ z.string().optional().describe(description);
25
+
26
+ export const crudPagePrompt: MapoPrompt<{
27
+ resource?: string;
28
+ fields?: string;
29
+ }> = {
30
+ name: "mapo-crud-page",
31
+ title: "Build a CRUD page",
32
+ description:
33
+ "List + detail pages for a resource, following Mapo's canonical pattern.",
34
+ argsSchema: {
35
+ resource: optional("Resource name, e.g. 'articles'"),
36
+ fields: optional("Fields to edit, e.g. 'title, body, status, cover image'"),
37
+ },
38
+ render: ({
39
+ resource,
40
+ fields,
41
+ }) => `Build the admin pages for ${resource ?? "a resource I will name"} in this Mapo project${
42
+ fields ? `, editing: ${fields}` : ""
43
+ }.
44
+
45
+ Follow this order and do not skip a step:
46
+ 1. mapo_inspect_app — see which field types are registered, which components exist and how the app is configured.
47
+ 2. mapo_list_field_types — pick the right \`type\` for each field, and read the \`attrs\` it accepts. Never invent a type.
48
+ 3. mapo_scaffold with kind "list-page", then kind "detail-page", passing \`fields\` as \`key:type:Label\` specs. Review the output before writing anything.
49
+ 4. mapo_component_api for MapoList and MapoDetail if you need a prop, slot or event that the scaffold does not cover.
50
+
51
+ Then adapt the generated code to the real backend payload, and tell me which endpoints it expects.`,
52
+ };
53
+
54
+ export const customFieldPrompt: MapoPrompt<{
55
+ type?: string;
56
+ behaviour?: string;
57
+ }> = {
58
+ name: "mapo-custom-field",
59
+ title: "Create a custom field type",
60
+ description:
61
+ "A new field component plus its registration in the form registry.",
62
+ argsSchema: {
63
+ type: optional("Type name, e.g. 'star-rating'"),
64
+ behaviour: optional("What the field should do"),
65
+ },
66
+ render: ({
67
+ type,
68
+ behaviour,
69
+ }) => `Add a custom form field type${type ? ` called \`${type}\`` : ""} to this Mapo project${
70
+ behaviour ? `: ${behaviour}` : ""
71
+ }.
72
+
73
+ Steps:
74
+ 1. mapo_list_field_types — check no built-in type already does this; overriding a built-in is a different decision than adding one.
75
+ 2. mapo_get_doc { path: "uikit/form/registry.md" } — the registration contract.
76
+ 3. mapo_scaffold with kind "custom-field" — it generates both the component and the plugin that registers the type.
77
+ 4. Implement the component body. It must accept \`modelValue\`, \`descriptor\`, \`errors\`, \`readonly\`, \`disabled\` and emit \`update:modelValue\`. Nothing else.
78
+
79
+ Remember that types registered at runtime are invisible to mapo_inspect_app, which reads a build-time snapshot.`,
80
+ };
81
+
82
+ export const debugFormPrompt: MapoPrompt<{ symptom?: string }> = {
83
+ name: "mapo-debug-form",
84
+ title: "Debug a Mapo form",
85
+ description:
86
+ "Diagnose a form that does not render, validate or save as expected.",
87
+ argsSchema: {
88
+ symptom: optional("What goes wrong, e.g. 'the select is empty'"),
89
+ },
90
+ render: ({
91
+ symptom,
92
+ }) => `A Mapo form is not behaving${symptom ? `: ${symptom}` : ""}. Diagnose it.
93
+
94
+ Steps:
95
+ 1. mapo_doctor — rule out a configuration problem before reading any code.
96
+ 2. mapo_inspect_app { include: ["fields", "config"] } — confirm the field type used is actually registered.
97
+ 3. mapo_list_field_types { type: "<the type>" } — check the descriptor's \`attrs\` against what the code passes; a missing required attr is the usual cause of an empty or inert field.
98
+ 4. mapo_search_docs for the specific behaviour (validation, translatable fields, repeater, accessors) and read the section with mapo_get_doc.
99
+
100
+ Report the cause before proposing a fix, and quote the doc path you relied on.`,
101
+ };
102
+
103
+ export const migratePrompt: MapoPrompt<{ area?: string }> = {
104
+ name: "mapo-migrate-v1",
105
+ title: "Migrate from Mapo v1",
106
+ description: "Port v1 code to the v2 APIs.",
107
+ argsSchema: {
108
+ area: optional("What to migrate, e.g. 'the list configuration'"),
109
+ },
110
+ render: ({
111
+ area,
112
+ }) => `Migrate this code from Mapo v1 to v2${area ? `, focusing on ${area}` : ""}.
113
+
114
+ Steps:
115
+ 1. mapo_get_doc { path: "migration/v1-to-v2.md" } — read it before changing anything.
116
+ 2. mapo_component_api / mapo_list_field_types for every symbol you touch: v1 names survive in training data long after they stop existing, so check each one against the installed source.
117
+ 3. mapo_search_docs for anything the migration page does not cover.
118
+
119
+ Do not port v1 patterns that v2 replaced (Vuex stores, Axios instances, config objects where v2 takes declarative props). Point them out instead.`,
120
+ };
121
+
122
+ export const themePrompt: MapoPrompt<{ goal?: string }> = {
123
+ name: "mapo-theme",
124
+ title: "Restyle the admin",
125
+ description:
126
+ "Change the look of a Mapo admin, from tokens to full component replacement.",
127
+ argsSchema: {
128
+ goal: optional(
129
+ "What should change, e.g. 'brand colours and a denser sidebar'",
130
+ ),
131
+ },
132
+ render: ({ goal }) => `Restyle this Mapo admin${goal ? `: ${goal}` : ""}.
133
+
134
+ Pick the lightest layer that does the job, in this order:
135
+ 1. mapo_get_doc { path: "howto/theming.md" } — CSS tokens and Nuxt UI defaults cover most requests.
136
+ 2. mapo_scaffold with kind "theme-override" for the token file and the nuxt.config fragment.
137
+ 3. Layout slots, if the change is structural — mapo_component_api on the layout components to see which slots exist.
138
+ 4. The MapoOverride system only as a last resort: mapo_get_doc { path: "uikit/mapoverride.md" }. Replacing a component means owning its updates.
139
+
140
+ Say which layer you chose and why.`,
141
+ };
142
+
143
+ export const PROMPTS = [
144
+ crudPagePrompt,
145
+ customFieldPrompt,
146
+ debugFormPrompt,
147
+ migratePrompt,
148
+ themePrompt,
149
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
150
+ ] as Array<MapoPrompt<any>>;