@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
@@ -0,0 +1,300 @@
1
+ /**
2
+ * API-surface tools: components, form field types and composables, all read
3
+ * from source at build time rather than from prose.
4
+ *
5
+ * These answer the questions models get wrong most often — which props a
6
+ * component takes, which `attrs` a field type accepts, what a composable
7
+ * returns — so the output is deliberately dense and quotes real types.
8
+ */
9
+ import { z } from "zod";
10
+ import { defineMapoTool } from "../tool-spec.js";
11
+ import type { AnyMapoToolSpec, MapoToolContext } from "../tool-spec.js";
12
+ import type {
13
+ ApiMember,
14
+ ComponentApi,
15
+ ComposableApi,
16
+ FieldTypeApi,
17
+ } from "../types.js";
18
+
19
+ const READ_ONLY = {
20
+ readOnlyHint: true,
21
+ destructiveHint: false,
22
+ idempotentHint: true,
23
+ openWorldHint: false,
24
+ } as const;
25
+
26
+ function renderMembers(title: string, members: ApiMember[]): string {
27
+ if (!members.length) return `**${title}**: none\n`;
28
+
29
+ const lines = members.map((member) => {
30
+ const type = member.type ? `: \`${member.type}\`` : "";
31
+ const required = member.required ? " **required**" : "";
32
+ const fallback =
33
+ member.default !== undefined ? ` (default \`${member.default}\`)` : "";
34
+ const description = member.description ? ` — ${member.description}` : "";
35
+ return `- \`${member.name}\`${type}${required}${fallback}${description}`;
36
+ });
37
+
38
+ return `**${title}** (${members.length})\n${lines.join("\n")}\n`;
39
+ }
40
+
41
+ function renderDocs(docs: string[]): string {
42
+ return docs.length
43
+ ? `\nDocs: ${docs.map((doc) => `\`${doc}\``).join(", ")}\n`
44
+ : "";
45
+ }
46
+
47
+ /** Exact match first, then substring, so `list` finds `MapoList`. */
48
+ function findByName<T extends { name: string }>(
49
+ entries: T[],
50
+ name: string,
51
+ ): T | undefined {
52
+ const needle = name.toLowerCase();
53
+ return (
54
+ entries.find((entry) => entry.name.toLowerCase() === needle) ??
55
+ entries.find((entry) => entry.name.toLowerCase() === `mapo${needle}`) ??
56
+ entries.find((entry) => entry.name.toLowerCase().includes(needle))
57
+ );
58
+ }
59
+
60
+ function suggest<T extends { name: string }>(
61
+ entries: T[],
62
+ name: string,
63
+ limit = 8,
64
+ ): string {
65
+ const needle = name.toLowerCase();
66
+ const close = entries
67
+ .filter((entry) => {
68
+ const candidate = entry.name.toLowerCase();
69
+ return (
70
+ [...needle].some((char) => candidate.includes(char)) &&
71
+ candidate.length > 0
72
+ );
73
+ })
74
+ .slice(0, limit)
75
+ .map((entry) => entry.name);
76
+
77
+ return close.length ? `\n\nAvailable: ${close.join(", ")}` : "";
78
+ }
79
+
80
+ interface ComponentApiArgs {
81
+ name: string;
82
+ include?: Array<"props" | "events" | "slots" | "exposed">;
83
+ }
84
+
85
+ function renderComponent(
86
+ component: ComponentApi,
87
+ include?: ComponentApiArgs["include"],
88
+ ): string {
89
+ const wanted = include?.length ? new Set(include) : null;
90
+ const sections: string[] = [];
91
+
92
+ if (!wanted || wanted.has("props"))
93
+ sections.push(renderMembers("Props", component.props));
94
+ if (!wanted || wanted.has("events"))
95
+ sections.push(renderMembers("Events", component.events));
96
+ if (!wanted || wanted.has("slots"))
97
+ sections.push(renderMembers("Slots", component.slots));
98
+ if ((!wanted || wanted.has("exposed")) && component.exposed.length) {
99
+ sections.push(renderMembers("Exposed", component.exposed));
100
+ }
101
+
102
+ return (
103
+ `# ${component.name}\n` +
104
+ `package: \`${component.pkg}\` · source: \`${component.file}\`\n` +
105
+ (component.description ? `\n${component.description}\n` : "") +
106
+ `\n${sections.join("\n")}` +
107
+ renderDocs(component.docs)
108
+ );
109
+ }
110
+
111
+ export const componentApiTool = defineMapoTool({
112
+ name: "mapo_component_api",
113
+ title: "Mapo component API",
114
+ description:
115
+ "Props, events, slots and exposed methods of a Mapo component, extracted from its source " +
116
+ "(not from the docs, which can lag behind). Call this before using any Mapo* component; " +
117
+ "omit `name` filters to see what exists.",
118
+ inputSchema: {
119
+ name: z
120
+ .string()
121
+ .describe(
122
+ "Component name, e.g. 'MapoList'. Partial names work ('list', 'detail').",
123
+ ),
124
+ include: z
125
+ .array(z.enum(["props", "events", "slots", "exposed"]))
126
+ .optional()
127
+ .describe("Limit the response to these sections"),
128
+ },
129
+ annotations: READ_ONLY,
130
+ inputExamples: [
131
+ { name: "MapoList" },
132
+ { name: "MapoDetail", include: ["slots"] },
133
+ ],
134
+ run: (args: ComponentApiArgs, context: MapoToolContext) => {
135
+ const { components } = context.api();
136
+ const component = findByName(components, args.name);
137
+
138
+ if (!component) {
139
+ return (
140
+ `No Mapo component matches "${args.name}".` +
141
+ suggest(components, args.name) +
142
+ `\n\n${components.length} components are available; ask for one by name.`
143
+ );
144
+ }
145
+
146
+ return renderComponent(component, args.include);
147
+ },
148
+ });
149
+
150
+ interface FieldTypesArgs {
151
+ type?: string;
152
+ }
153
+
154
+ /** Minimal descriptor skeleton, listing only what the type actually requires. */
155
+ function exampleDescriptor(field: FieldTypeApi): string {
156
+ const requiredAttrs = field.attrs.filter((attr) => attr.required);
157
+ const attrs = requiredAttrs.length
158
+ ? `, attrs: { ${requiredAttrs.map((attr) => `${attr.name}: …`).join(", ")} }`
159
+ : "";
160
+ return `{ key: "…", type: "${field.type}", label: "…"${attrs} }`;
161
+ }
162
+
163
+ function renderFieldType(field: FieldTypeApi, common: ApiMember[]): string {
164
+ const defaults = field.defaultAttrs
165
+ ? `registry defaults: \`${JSON.stringify(field.defaultAttrs)}\`\n`
166
+ : "";
167
+
168
+ return (
169
+ `# Field type \`${field.type}\`\n` +
170
+ (field.component
171
+ ? `component: \`${field.component}\``
172
+ : "component: (unmapped)") +
173
+ (field.descriptor ? ` · descriptor: \`${field.descriptor}\`` : "") +
174
+ (field.hasAccessor ? " · has a default get/set accessor" : "") +
175
+ "\n" +
176
+ defaults +
177
+ (field.description ? `\n${field.description}\n` : "") +
178
+ `\n\`\`\`ts\n${exampleDescriptor(field)}\n\`\`\`\n\n` +
179
+ renderMembers("attrs", field.attrs) +
180
+ `\nEvery descriptor also accepts: ${common.map((member) => `\`${member.name}\``).join(", ")}. ` +
181
+ `Call mapo_list_field_types with no argument for the full list of types.` +
182
+ renderDocs(field.docs)
183
+ );
184
+ }
185
+
186
+ export const fieldTypesTool = defineMapoTool({
187
+ name: "mapo_list_field_types",
188
+ title: "Mapo form field types",
189
+ description:
190
+ "The form field registry: every `type` a FieldDescriptor accepts, the component behind it, " +
191
+ "and the exact `attrs` it takes — read from source. Use this before writing any field " +
192
+ "descriptor; never invent a field type or an attr.",
193
+ inputSchema: {
194
+ type: z
195
+ .string()
196
+ .optional()
197
+ .describe(
198
+ "Field type to detail, e.g. 'select'. Omit to list every type.",
199
+ ),
200
+ },
201
+ annotations: READ_ONLY,
202
+ inputExamples: [{}, { type: "repeater" }],
203
+ run: (args: FieldTypesArgs, context: MapoToolContext) => {
204
+ const { fieldTypes, fieldCommon } = context.api();
205
+
206
+ if (args.type) {
207
+ const needle = args.type.toLowerCase();
208
+ const field = fieldTypes.find(
209
+ (entry) => entry.type.toLowerCase() === needle,
210
+ );
211
+ if (!field) {
212
+ return (
213
+ `No field type "${args.type}". Available: ` +
214
+ `${fieldTypes.map((entry) => entry.type).join(", ")}.\n\n` +
215
+ `Custom types are registered with defineFormField() — see uikit/form/registry.md.`
216
+ );
217
+ }
218
+ return renderFieldType(field, fieldCommon);
219
+ }
220
+
221
+ const lines = fieldTypes.map((field) => {
222
+ const attrs = field.attrs.length
223
+ ? ` — attrs: ${field.attrs.map((attr) => attr.name).join(", ")}`
224
+ : "";
225
+ return `- \`${field.type}\`${field.component ? ` → ${field.component}` : ""}${attrs}`;
226
+ });
227
+
228
+ return (
229
+ `${fieldTypes.length} registered field types:\n\n${lines.join("\n")}\n\n` +
230
+ `Shared descriptor properties: ${fieldCommon.map((member) => `\`${member.name}\``).join(", ")}.\n` +
231
+ `Call mapo_list_field_types({ type }) for the full contract of one type.`
232
+ );
233
+ },
234
+ });
235
+
236
+ interface ComposableArgs {
237
+ name?: string;
238
+ }
239
+
240
+ function renderComposable(composable: ComposableApi): string {
241
+ return (
242
+ `# ${composable.name}\n` +
243
+ `package: \`${composable.pkg}\` · source: \`${composable.file}\` · auto-imported\n` +
244
+ (composable.description ? `\n${composable.description}\n` : "") +
245
+ (composable.signature
246
+ ? `\n\`\`\`ts\n${composable.name}: ${composable.signature}\n\`\`\`\n`
247
+ : "") +
248
+ renderDocs(composable.docs)
249
+ );
250
+ }
251
+
252
+ export const composableApiTool = defineMapoTool({
253
+ name: "mapo_composable_api",
254
+ title: "Mapo composables",
255
+ description:
256
+ "The composables and stores Mapo auto-imports into an app (useCrud, useMapoAuth, useMapo, " +
257
+ "useMediaStore…), with their real signatures. Omit `name` to list everything available.",
258
+ inputSchema: {
259
+ name: z
260
+ .string()
261
+ .optional()
262
+ .describe("Composable name, e.g. 'useCrud'. Partial names work."),
263
+ },
264
+ annotations: READ_ONLY,
265
+ inputExamples: [{}, { name: "useCrud" }],
266
+ run: (args: ComposableArgs, context: MapoToolContext) => {
267
+ const { composables } = context.api();
268
+
269
+ if (args.name) {
270
+ const composable = findByName(composables, args.name);
271
+ if (!composable) {
272
+ return `No auto-imported composable matches "${args.name}".${suggest(composables, args.name)}`;
273
+ }
274
+ return renderComposable(composable);
275
+ }
276
+
277
+ const byPackage = new Map<string, string[]>();
278
+ for (const composable of composables) {
279
+ const list = byPackage.get(composable.pkg) ?? [];
280
+ list.push(composable.name);
281
+ byPackage.set(composable.pkg, list);
282
+ }
283
+
284
+ const sections = [...byPackage.entries()].map(
285
+ ([pkg, names]) => `**${pkg}**: ${names.join(", ")}`,
286
+ );
287
+
288
+ return (
289
+ `${composables.length} auto-imported composables:\n\n${sections.join("\n")}\n\n` +
290
+ `Call mapo_composable_api({ name }) for a signature.`
291
+ );
292
+ },
293
+ });
294
+
295
+ /** API-surface tools. Static: they read the bundled extraction, not the app. */
296
+ export const apiTools: AnyMapoToolSpec[] = [
297
+ componentApiTool,
298
+ fieldTypesTool,
299
+ composableApiTool,
300
+ ];
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Live tools: they describe the app the server runs inside.
3
+ *
4
+ * Only the Nuxt module can answer these — the stdio CLI knows Mapo but not the
5
+ * project using it — so when the manifest is absent they explain how to get it
6
+ * instead of failing or, worse, guessing.
7
+ */
8
+ import { z } from "zod";
9
+ import { DOCTOR_BLIND_SPOTS, runDoctor } from "../doctor.js";
10
+ import { defineMapoTool } from "../tool-spec.js";
11
+ import type { AnyMapoToolSpec, MapoToolContext } from "../tool-spec.js";
12
+ import type { MapoAppManifest } from "../../../index.js";
13
+
14
+ const READ_ONLY = {
15
+ readOnlyHint: true,
16
+ destructiveHint: false,
17
+ idempotentHint: true,
18
+ openWorldHint: false,
19
+ } as const;
20
+
21
+ const NO_APP =
22
+ "This tool needs the running app and is only served over HTTP.\n\n" +
23
+ "Start the dev server (`pnpm dev`) and point the client at the URL it prints at startup: " +
24
+ "`http://localhost:3000/mcp/mapo` by default, under the app's `app.baseURL` when it has one. " +
25
+ "The stdio server (`mapo-mcp serve`) knows the framework and its documentation, but not the " +
26
+ "project using it.";
27
+
28
+ type InspectSection =
29
+ | "modules"
30
+ | "config"
31
+ | "fields"
32
+ | "components"
33
+ | "routes"
34
+ | "locales";
35
+
36
+ interface InspectArgs {
37
+ include?: InspectSection[];
38
+ }
39
+
40
+ function renderModules(manifest: MapoAppManifest): string {
41
+ const installed = manifest.modules
42
+ .map(
43
+ (module) =>
44
+ `- \`${module.name}\`${module.version ? ` @ ${module.version}` : ""}`,
45
+ )
46
+ .join("\n");
47
+
48
+ return (
49
+ `## Installed Mapo modules\n${installed || "- (none)"}\n\n` +
50
+ `Declaration order in nuxt.config: ${manifest.moduleOrder.map((name) => `\`${name}\``).join(" → ") || "(none)"}\n`
51
+ );
52
+ }
53
+
54
+ function renderConfig(manifest: MapoAppManifest): string {
55
+ const entries = Object.entries(manifest.config);
56
+ if (!entries.length) return "## Configuration\n(no public Mapo config)\n";
57
+
58
+ const blocks = entries.map(
59
+ ([key, value]) =>
60
+ `### ${key}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``,
61
+ );
62
+ return `## Configuration (public runtime config)\n${blocks.join("\n")}\n`;
63
+ }
64
+
65
+ function renderFields(manifest: MapoAppManifest): string {
66
+ const registry = manifest.fieldTypes.filter(
67
+ (field) => field.source === "default",
68
+ );
69
+ const custom = manifest.fieldTypes.filter(
70
+ (field) => field.source === "config",
71
+ );
72
+
73
+ return (
74
+ `## Registered field types (${manifest.fieldTypes.length})\n` +
75
+ `- from the registry: ${registry.map((field) => `\`${field.type}\``).join(", ") || "(none)"}\n` +
76
+ (custom.length
77
+ ? `- added in nuxt.config: ${custom.map((field) => `\`${field.type}\``).join(", ")}\n`
78
+ : "") +
79
+ "- types registered at runtime with `defineFormField()` are not visible here\n"
80
+ );
81
+ }
82
+
83
+ function renderComponents(manifest: MapoAppManifest): string {
84
+ return (
85
+ `## Available Mapo components (${manifest.components.length})\n` +
86
+ `${manifest.components.map((name) => `\`${name}\``).join(", ") || "(none)"}\n\n` +
87
+ "Ask mapo_component_api for the props of any of them.\n"
88
+ );
89
+ }
90
+
91
+ function renderRoutes(manifest: MapoAppManifest): string {
92
+ const lines = manifest.routes.map((route) => `- \`${route.path}\``);
93
+ return `## Routes (${manifest.routes.length})\n${lines.join("\n") || "- (none)"}\n`;
94
+ }
95
+
96
+ export const inspectAppTool = defineMapoTool({
97
+ name: "mapo_inspect_app",
98
+ title: "Inspect this Mapo app",
99
+ description:
100
+ "Report how Mapo is actually set up in the project currently running: installed modules and " +
101
+ "versions, public Mapo configuration, registered form field types, available Mapo components, " +
102
+ "routes and locales. Call this before writing code for the project, so the code matches its " +
103
+ "real configuration instead of the defaults.",
104
+ inputSchema: {
105
+ include: z
106
+ .array(
107
+ z.enum([
108
+ "modules",
109
+ "config",
110
+ "fields",
111
+ "components",
112
+ "routes",
113
+ "locales",
114
+ ]),
115
+ )
116
+ .optional()
117
+ .describe("Limit the report to these sections"),
118
+ },
119
+ annotations: READ_ONLY,
120
+ inputExamples: [{}, { include: ["fields", "config"] }],
121
+ run: (args: InspectArgs, context: MapoToolContext) => {
122
+ const manifest = context.manifest();
123
+ if (!manifest) return NO_APP;
124
+
125
+ const wanted = args.include?.length ? new Set(args.include) : null;
126
+ const want = (section: InspectSection) => !wanted || wanted.has(section);
127
+ const parts: string[] = [];
128
+
129
+ if (want("modules")) parts.push(renderModules(manifest));
130
+ if (want("config")) parts.push(renderConfig(manifest));
131
+ if (want("fields")) parts.push(renderFields(manifest));
132
+ if (want("components")) parts.push(renderComponents(manifest));
133
+ if (want("routes")) parts.push(renderRoutes(manifest));
134
+ if (want("locales")) {
135
+ parts.push(
136
+ `## Locales\n${manifest.locales.join(", ") || "(i18n not configured)"}\n`,
137
+ );
138
+ }
139
+
140
+ return (
141
+ `# Mapo setup of \`${manifest.rootDir}\`\n\n${parts.join("\n")}\n` +
142
+ `Snapshot taken when the dev server started; restart it after changing nuxt.config.`
143
+ );
144
+ },
145
+ });
146
+
147
+ export const doctorTool = defineMapoTool({
148
+ name: "mapo_doctor",
149
+ title: "Diagnose this Mapo app",
150
+ description:
151
+ "Check the running project for known Mapo misconfigurations — module ordering, missing login " +
152
+ "route, untouched auth endpoints, locales without catalogs, media endpoints — and return each " +
153
+ "problem with the exact fix. Run it when something behaves unexpectedly, or before shipping.",
154
+ inputSchema: {
155
+ severity: z
156
+ .enum(["error", "warning", "info"])
157
+ .optional()
158
+ .describe("Only report findings at this severity or above"),
159
+ },
160
+ annotations: READ_ONLY,
161
+ inputExamples: [{}, { severity: "error" }],
162
+ run: (
163
+ args: { severity?: "error" | "warning" | "info" },
164
+ context: MapoToolContext,
165
+ ) => {
166
+ const manifest = context.manifest();
167
+ if (!manifest) return NO_APP;
168
+
169
+ const threshold = { error: 0, warning: 1, info: 2 };
170
+ const minimum = threshold[args.severity ?? "info"];
171
+ const findings = runDoctor(manifest).filter(
172
+ (finding) => threshold[finding.severity] <= minimum,
173
+ );
174
+
175
+ const blindSpots = `\n_Not checked: ${DOCTOR_BLIND_SPOTS.join("; ")}._`;
176
+
177
+ if (!findings.length) {
178
+ return `No problem found in \`${manifest.rootDir}\`.\n${blindSpots}`;
179
+ }
180
+
181
+ const icons = { error: "✖", warning: "▲", info: "ℹ" } as const;
182
+ const blocks = findings.map(
183
+ (finding) =>
184
+ `### ${icons[finding.severity]} ${finding.rule} (${finding.severity})\n` +
185
+ `${finding.message}\n` +
186
+ (finding.fix ? `\n**Fix**: ${finding.fix}\n` : "") +
187
+ (finding.doc ? `Docs: \`${finding.doc}\`\n` : ""),
188
+ );
189
+
190
+ const errors = findings.filter(
191
+ (finding) => finding.severity === "error",
192
+ ).length;
193
+ return (
194
+ `${findings.length} finding(s)${errors ? `, ${errors} of which block the app` : ""}:\n\n` +
195
+ `${blocks.join("\n")}${blindSpots}`
196
+ );
197
+ },
198
+ });
199
+
200
+ /** Tools that require the running app. */
201
+ export const appTools: AnyMapoToolSpec[] = [inspectAppTool, doctorTool];
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Backend schema tool: turns the API the app talks to into Mapo descriptors.
3
+ *
4
+ * This is the last gap between "knows Mapo" and "knows this project": the
5
+ * assistant can now read the real serializers instead of guessing which fields
6
+ * a model has and which types they should use.
7
+ */
8
+ import { z } from "zod";
9
+ import {
10
+ listModels,
11
+ renderFields,
12
+ resolveSchema,
13
+ toFields,
14
+ toScaffoldSpecs,
15
+ } from "../openapi.js";
16
+ import {
17
+ SchemaUnavailableError,
18
+ loadOpenApiDocument,
19
+ } from "../schema-source.js";
20
+ import { defineMapoTool } from "../tool-spec.js";
21
+ import type { AnyMapoToolSpec, MapoToolContext } from "../tool-spec.js";
22
+
23
+ const READ_ONLY = {
24
+ readOnlyHint: true,
25
+ destructiveHint: false,
26
+ idempotentHint: true,
27
+ // It reaches a backend that is not part of this server.
28
+ openWorldHint: true,
29
+ } as const;
30
+
31
+ type Action = "list_models" | "describe_model" | "to_fields";
32
+
33
+ interface BackendArgs {
34
+ action: Action;
35
+ model?: string;
36
+ url?: string;
37
+ includeReadOnly?: boolean;
38
+ }
39
+
40
+ const NO_SOURCE =
41
+ "No schema source configured.\n\n" +
42
+ "Set `mapo.mcp.backend.schemaUrl` in nuxt.config (drf-spectacular: " +
43
+ "`http://localhost:8000/api/schema/?format=json`), export `MAPO_BACKEND_SCHEMA_URL`, " +
44
+ "or pass `url` to this tool. A local path to an exported schema works too.";
45
+
46
+ export const backendSchemaTool = defineMapoTool({
47
+ name: "mapo_backend_schema",
48
+ title: "Backend schema → Mapo fields",
49
+ description:
50
+ "Read the backend's OpenAPI/DRF schema and turn a serializer into Mapo field descriptors: " +
51
+ "types, choices, required and read-only flags, and the endpoint of every relation. " +
52
+ "Use it before writing a form against a real API, and feed its output to mapo_scaffold.",
53
+ inputSchema: {
54
+ action: z
55
+ .enum(["list_models", "describe_model", "to_fields"])
56
+ .describe(
57
+ "list the serializers, inspect one, or map one to field descriptors",
58
+ ),
59
+ model: z.string().optional().describe("Component name, e.g. 'Article'"),
60
+ url: z
61
+ .string()
62
+ .optional()
63
+ .describe(
64
+ "Schema URL or local file path; defaults to the configured source",
65
+ ),
66
+ includeReadOnly: z
67
+ .boolean()
68
+ .optional()
69
+ .describe(
70
+ "Keep server-computed properties (id, timestamps) as readonly fields",
71
+ ),
72
+ },
73
+ annotations: READ_ONLY,
74
+ inputExamples: [
75
+ { action: "list_models" },
76
+ { action: "to_fields", model: "Article" },
77
+ ],
78
+ run: async (args: BackendArgs, context: MapoToolContext) => {
79
+ const backend = context.backend();
80
+ const source = args.url ?? backend.schemaUrl;
81
+ if (!source) return NO_SOURCE;
82
+
83
+ let document;
84
+ try {
85
+ document = await loadOpenApiDocument(source, {
86
+ token: backend.token,
87
+ rootDir: context.rootDir(),
88
+ });
89
+ } catch (error) {
90
+ if (error instanceof SchemaUnavailableError) return error.message;
91
+ throw error;
92
+ }
93
+
94
+ const title = document.info?.title ? `${document.info.title} — ` : "";
95
+
96
+ if (args.action === "list_models") {
97
+ const models = listModels(document);
98
+ if (!models.length) return `${source} declares no component schemas.`;
99
+
100
+ const lines = models.map(
101
+ (model) =>
102
+ `- \`${model.name}\` (${model.fieldCount} properties)` +
103
+ (model.endpoint
104
+ ? ` → \`${model.endpoint}\``
105
+ : " — no list endpoint declared"),
106
+ );
107
+
108
+ return (
109
+ `# ${title}${models.length} models\nsource: \`${source}\`\n\n${lines.join("\n")}\n\n` +
110
+ 'Call this tool again with `action: "to_fields"` and a model name.'
111
+ );
112
+ }
113
+
114
+ if (!args.model) {
115
+ return `\`${args.action}\` needs a \`model\`. Run \`action: "list_models"\` to see what exists.`;
116
+ }
117
+
118
+ const schema = document.components?.schemas?.[args.model];
119
+ if (!schema) {
120
+ const available = listModels(document)
121
+ .map((model) => model.name)
122
+ .slice(0, 30)
123
+ .join(", ");
124
+ return `No model \`${args.model}\` in ${source}. Available: ${available}.`;
125
+ }
126
+
127
+ if (args.action === "describe_model") {
128
+ const required = new Set(schema.required ?? []);
129
+ const rows = Object.entries(schema.properties ?? {}).map(
130
+ ([key, property]) => {
131
+ const { schema: resolved, ref } = resolveSchema(document, property);
132
+ const kind = ref ?? resolved.type ?? "unknown";
133
+ const flags = [
134
+ required.has(key) ? "required" : "",
135
+ resolved.readOnly ? "read-only" : "",
136
+ resolved.nullable ? "nullable" : "",
137
+ resolved.enum?.length ? `enum(${resolved.enum.length})` : "",
138
+ ]
139
+ .filter(Boolean)
140
+ .join(", ");
141
+ return `- \`${key}\`: ${kind}${resolved.format ? ` (${resolved.format})` : ""}${flags ? ` — ${flags}` : ""}`;
142
+ },
143
+ );
144
+
145
+ return (
146
+ `# ${args.model}\nsource: \`${source}\`\n` +
147
+ (schema.description ? `\n${schema.description}\n` : "") +
148
+ `\n${rows.join("\n") || "(no properties)"}\n\n` +
149
+ `Map it with \`action: "to_fields"\`.`
150
+ );
151
+ }
152
+
153
+ // to_fields
154
+ const knownTypes = new Set(
155
+ context.api().fieldTypes.map((field) => field.type),
156
+ );
157
+ const result = toFields(document, args.model, {
158
+ knownTypes,
159
+ ...(args.includeReadOnly ? { includeReadOnly: true } : {}),
160
+ })!;
161
+
162
+ const skipped = result.skipped.length
163
+ ? `\n## Skipped\n${result.skipped.map((entry) => `- \`${entry.key}\` — ${entry.reason}`).join("\n")}\n`
164
+ : "";
165
+
166
+ const notes = result.notes.length
167
+ ? `\n${result.notes.map((note) => `- ${note}`).join("\n")}\n`
168
+ : "";
169
+
170
+ const specs = toScaffoldSpecs(result);
171
+ const scaffoldLine = specs.length
172
+ ? `\n## Scaffold it\n\`\`\`json\n${JSON.stringify(
173
+ {
174
+ kind: "detail-page",
175
+ name: args.model.toLowerCase(),
176
+ ...(result.endpoint ? { endpoint: result.endpoint } : {}),
177
+ fields: specs,
178
+ },
179
+ null,
180
+ 2,
181
+ )}\n\`\`\`\nPass that to mapo_scaffold.\n`
182
+ : "";
183
+
184
+ return (
185
+ `# ${args.model} → ${result.fields.length} field descriptors\n` +
186
+ `source: \`${source}\`${result.endpoint ? ` · endpoint: \`${result.endpoint}\`` : ""}\n\n` +
187
+ `\`\`\`ts\n${renderFields(result)}\n\`\`\`\n` +
188
+ skipped +
189
+ notes +
190
+ scaffoldLine +
191
+ "\nTypes were checked against the registry of this app: a property whose mapping is not " +
192
+ "registered is skipped rather than emitted."
193
+ );
194
+ },
195
+ });
196
+
197
+ export const backendTools: AnyMapoToolSpec[] = [backendSchemaTool];