@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,282 @@
1
+ /**
2
+ * Query side of the knowledge base: BM25 ranking plus snippet extraction.
3
+ *
4
+ * Deliberately dependency-free and synchronous — it runs both inside Nitro
5
+ * (dev server) and inside the stdio CLI.
6
+ */
7
+ import { tokenize } from "./tokenize.js";
8
+ import type { DocChunk, DocsKnowledge, SearchHit } from "./types.js";
9
+
10
+ const K1 = 1.5;
11
+ const B = 0.75;
12
+ const SNIPPET_CHARS = 360;
13
+
14
+ /** Share of a page's other matching sections added to each of its chunks. */
15
+ const PAGE_CONTEXT_WEIGHT = 0.2;
16
+ /** Per distinct query term found in the page title or path. */
17
+ const TITLE_BOOST_STEP = 0.15;
18
+ const TITLE_BOOST_CAP = 1.5;
19
+ /** A page may not take over the whole result list. */
20
+ const MAX_HITS_PER_PAGE = 2;
21
+ /** Applied to API-reference chunks unless the query is about an API surface. */
22
+ const REFERENCE_PENALTY = 0.75;
23
+ /** Words signalling the user really wants the reference tables. */
24
+ const REFERENCE_INTENT =
25
+ /\b(prop|props|slot|slots|emit|emits|event|events|api|signature|reference|type)\b/i;
26
+ /**
27
+ * Path segments too generic to signal topicality — boosting on them would
28
+ * favour reference pages (`uikit/api.md`) for every query.
29
+ */
30
+ const GENERIC_IDENTITY_TOKENS = new Set([
31
+ "api",
32
+ "index",
33
+ "doc",
34
+ "overview",
35
+ "reference",
36
+ "uikit",
37
+ "modul",
38
+ "module",
39
+ "howto",
40
+ "guid",
41
+ "guide",
42
+ "migrat",
43
+ "migration",
44
+ "md",
45
+ ]);
46
+
47
+ export interface SearchOptions {
48
+ /** Restrict to a docs area: `howto`, `guide`, `uikit`, `modules`, `migration`. */
49
+ section?: string;
50
+ /** Restrict to a package, e.g. `@mapomodule/form` (bare `form` also works). */
51
+ pkg?: string;
52
+ limit?: number;
53
+ }
54
+
55
+ function matchesFilters(chunk: DocChunk, options: SearchOptions): boolean {
56
+ if (options.section) {
57
+ const wanted = options.section.toLowerCase();
58
+ if (chunk.section !== wanted && chunk.group !== wanted) return false;
59
+ }
60
+ if (options.pkg) {
61
+ const wanted = options.pkg.toLowerCase().replace(/^@mapomodule\//, "");
62
+ if (!chunk.pkg || !chunk.pkg.toLowerCase().includes(wanted)) return false;
63
+ }
64
+ return true;
65
+ }
66
+
67
+ /** Builds a short excerpt centred on the densest run of query terms. */
68
+ export function extractSnippet(text: string, query: string): string {
69
+ const words = query
70
+ .toLowerCase()
71
+ .split(/[^a-z0-9]+/)
72
+ .filter((word) => word.length > 2);
73
+
74
+ const haystack = text.toLowerCase();
75
+ let best = -1;
76
+ for (const word of words) {
77
+ const at = haystack.indexOf(word);
78
+ if (at !== -1 && (best === -1 || at < best)) best = at;
79
+ }
80
+
81
+ if (best === -1) {
82
+ return text.length > SNIPPET_CHARS
83
+ ? `${text.slice(0, SNIPPET_CHARS).trimEnd()}…`
84
+ : text;
85
+ }
86
+
87
+ const start = Math.max(0, best - Math.floor(SNIPPET_CHARS / 3));
88
+ const end = Math.min(text.length, start + SNIPPET_CHARS);
89
+ const slice = text.slice(start, end).trim();
90
+
91
+ return `${start > 0 ? "…" : ""}${slice}${end < text.length ? "…" : ""}`;
92
+ }
93
+
94
+ /** Ranked search over the bundled docs. Returns sections, never whole files. */
95
+ export function searchDocs(
96
+ knowledge: DocsKnowledge,
97
+ query: string,
98
+ options: SearchOptions = {},
99
+ ): SearchHit[] {
100
+ const { chunks, index } = knowledge;
101
+ const limit = options.limit ?? 5;
102
+ const queryTerms = tokenize(query);
103
+ if (!queryTerms.length || !index.total) return [];
104
+
105
+ const scores = new Map<number, number>();
106
+ const seenTerms = new Set<string>();
107
+
108
+ for (const term of queryTerms) {
109
+ if (seenTerms.has(term)) continue;
110
+ seenTerms.add(term);
111
+
112
+ const postings = index.terms[term];
113
+ if (!postings) continue;
114
+
115
+ // Standard BM25 idf, floored so very common terms still contribute a little.
116
+ const idf = Math.max(
117
+ 0.05,
118
+ Math.log(
119
+ 1 + (index.total - postings.length + 0.5) / (postings.length + 0.5),
120
+ ),
121
+ );
122
+
123
+ for (const [chunkIndex, frequency] of postings) {
124
+ const chunk = chunks[chunkIndex];
125
+ if (!chunk || !matchesFilters(chunk, options)) continue;
126
+
127
+ const length = index.lengths[chunkIndex] ?? 0;
128
+ const norm = 1 - B + (B * length) / (index.avgLength || 1);
129
+ const score = idf * ((frequency * (K1 + 1)) / (frequency + K1 * norm));
130
+ scores.set(chunkIndex, (scores.get(chunkIndex) ?? 0) + score);
131
+ }
132
+ }
133
+
134
+ // Sections of a page that is broadly about the topic beat an incidental
135
+ // mention elsewhere: give every chunk a share of its siblings' scores.
136
+ const pageTotals = new Map<string, number>();
137
+ for (const [chunkIndex, score] of scores) {
138
+ const { path } = chunks[chunkIndex]!;
139
+ pageTotals.set(path, (pageTotals.get(path) ?? 0) + score);
140
+ }
141
+
142
+ const phrase = query.trim().toLowerCase();
143
+ const distinctTerms = [...seenTerms];
144
+ const wantsReference = REFERENCE_INTENT.test(query);
145
+
146
+ const ranked = [...scores.entries()].map(([chunkIndex, score]) => {
147
+ const chunk = chunks[chunkIndex]!;
148
+ let final =
149
+ score +
150
+ PAGE_CONTEXT_WEIGHT * ((pageTotals.get(chunk.path) ?? score) - score);
151
+
152
+ // A query term in the title or the file path is a strong topical signal
153
+ // that BM25 dilutes across the whole section.
154
+ const identity = new Set(
155
+ tokenize(`${chunk.title} ${chunk.path.replace(/[/.\-_]/g, " ")}`),
156
+ );
157
+ const matched = distinctTerms.filter(
158
+ (term) => identity.has(term) && !GENERIC_IDENTITY_TOKENS.has(term),
159
+ ).length;
160
+ if (matched)
161
+ final *= Math.min(TITLE_BOOST_CAP, 1 + TITLE_BOOST_STEP * matched);
162
+
163
+ // Prop tables answer "what props does X take", not "how do I do Y".
164
+ if (chunk.kind === "reference" && !wantsReference)
165
+ final *= REFERENCE_PENALTY;
166
+
167
+ // Exact-phrase presence is a signal the bag of words misses entirely.
168
+ if (phrase.length > 6 && chunk.text.toLowerCase().includes(phrase))
169
+ final *= 1.5;
170
+
171
+ return [chunkIndex, final] as const;
172
+ });
173
+
174
+ const perPage = new Map<string, number>();
175
+
176
+ return ranked
177
+ .sort((a, b) => b[1] - a[1])
178
+ .filter(([chunkIndex]) => {
179
+ const { path } = chunks[chunkIndex]!;
180
+ const used = perPage.get(path) ?? 0;
181
+ if (used >= MAX_HITS_PER_PAGE) return false;
182
+ perPage.set(path, used + 1);
183
+ return true;
184
+ })
185
+ .slice(0, limit)
186
+ .map(([chunkIndex, score]) => {
187
+ const chunk = chunks[chunkIndex]!;
188
+ return {
189
+ id: chunk.id,
190
+ path: chunk.path,
191
+ section: chunk.section,
192
+ title: chunk.title,
193
+ heading: chunk.heading,
194
+ anchor: chunk.anchor,
195
+ score: Number(score.toFixed(3)),
196
+ snippet: extractSnippet(chunk.text, query),
197
+ tags: chunk.tags.slice(0, 8),
198
+ };
199
+ });
200
+ }
201
+
202
+ export interface GetDocResult {
203
+ path: string;
204
+ title: string;
205
+ /** Every heading of the page, so the caller can request a narrower slice. */
206
+ headings: string[];
207
+ content: string;
208
+ truncated: boolean;
209
+ }
210
+
211
+ /**
212
+ * Returns a whole page or a single section, rebuilt from its chunks.
213
+ * `heading` accepts the heading text or its anchor.
214
+ */
215
+ export function getDoc(
216
+ knowledge: DocsKnowledge,
217
+ path: string,
218
+ options: { heading?: string; maxChars?: number } = {},
219
+ ): GetDocResult | null {
220
+ const wantedPath = path.replace(/^\/+/, "").replace(/^docs\//, "");
221
+ const pageChunks = knowledge.chunks.filter(
222
+ (chunk) => chunk.path === wantedPath,
223
+ );
224
+ if (!pageChunks.length) return null;
225
+
226
+ const maxChars = options.maxChars ?? 8000;
227
+ const headings = [...new Set(pageChunks.map((chunk) => chunk.heading))];
228
+
229
+ let selected = pageChunks;
230
+ if (options.heading) {
231
+ const wanted = options.heading.toLowerCase();
232
+ selected = pageChunks.filter(
233
+ (chunk) =>
234
+ chunk.heading.toLowerCase() === wanted ||
235
+ chunk.anchor === wanted.replace(/^#/, ""),
236
+ );
237
+ if (!selected.length) selected = pageChunks;
238
+ }
239
+
240
+ const body = selected
241
+ .map((chunk) =>
242
+ chunk.level > 1
243
+ ? `${"#".repeat(chunk.level)} ${chunk.heading}\n\n${chunk.text}`
244
+ : chunk.text,
245
+ )
246
+ .join("\n\n");
247
+
248
+ return {
249
+ path: wantedPath,
250
+ title: pageChunks[0]!.title,
251
+ headings,
252
+ content:
253
+ body.length > maxChars
254
+ ? `${body.slice(0, maxChars)}\n\n…[truncated]`
255
+ : body,
256
+ truncated: body.length > maxChars,
257
+ };
258
+ }
259
+
260
+ /** Doc tree for the `mapo://knowledge/index` resource and `mapo_list_recipes`. */
261
+ export function listDocs(
262
+ knowledge: DocsKnowledge,
263
+ ): Array<{ path: string; title: string; section: string; headings: string[] }> {
264
+ const byPath = new Map<
265
+ string,
266
+ { path: string; title: string; section: string; headings: string[] }
267
+ >();
268
+
269
+ for (const chunk of knowledge.chunks) {
270
+ const entry = byPath.get(chunk.path) ?? {
271
+ path: chunk.path,
272
+ title: chunk.title,
273
+ section: chunk.section,
274
+ headings: [],
275
+ };
276
+ if (chunk.level > 1 && !entry.headings.includes(chunk.heading))
277
+ entry.headings.push(chunk.heading);
278
+ byPath.set(chunk.path, entry);
279
+ }
280
+
281
+ return [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path));
282
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Tokenizer shared by the index builder and the query side.
3
+ *
4
+ * Both sides MUST use this function: BM25 postings are keyed by the exact
5
+ * strings produced here, so any divergence silently breaks recall.
6
+ */
7
+
8
+ const STOPWORDS = new Set([
9
+ "a",
10
+ "an",
11
+ "and",
12
+ "are",
13
+ "as",
14
+ "at",
15
+ "be",
16
+ "but",
17
+ "by",
18
+ "can",
19
+ "do",
20
+ "does",
21
+ "for",
22
+ "from",
23
+ "how",
24
+ "i",
25
+ "if",
26
+ "in",
27
+ "into",
28
+ "is",
29
+ "it",
30
+ "its",
31
+ "me",
32
+ "my",
33
+ "of",
34
+ "on",
35
+ "or",
36
+ "our",
37
+ "so",
38
+ "that",
39
+ "the",
40
+ "their",
41
+ "them",
42
+ "then",
43
+ "there",
44
+ "these",
45
+ "they",
46
+ "this",
47
+ "to",
48
+ "was",
49
+ "we",
50
+ "were",
51
+ "what",
52
+ "when",
53
+ "where",
54
+ "which",
55
+ "who",
56
+ "will",
57
+ "with",
58
+ "you",
59
+ "your",
60
+ ]);
61
+
62
+ /** Words that must never be de-pluralised (`css` → `cs` would be nonsense). */
63
+ const NO_STEM_SUFFIX = /(?:ss|us|is|os)$/;
64
+
65
+ /**
66
+ * Suffix rules applied after de-pluralisation, first match wins.
67
+ * They exist to collapse morphological variants of the same concept:
68
+ * `paginate` / `paginated` / `paginating` / `pagination` → `paginat`.
69
+ * Only applied when the result keeps at least 4 characters.
70
+ */
71
+ const SUFFIX_RULES: Array<[RegExp, string]> = [
72
+ [/ation$/, "at"],
73
+ [/ition$/, "it"],
74
+ [/ing$/, ""],
75
+ [/edly$/, ""],
76
+ [/ed$/, ""],
77
+ [/ly$/, ""],
78
+ [/e$/, ""],
79
+ ];
80
+
81
+ const MIN_STEM_LENGTH = 4;
82
+
83
+ /** Splits `MapoListFilters` into `["mapolistfilters", "mapo", "list", "filters"]`. */
84
+ function splitIdentifier(word: string): string[] {
85
+ const parts = word
86
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
87
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
88
+ .split(/[\s_-]+/)
89
+ .filter(Boolean);
90
+ return parts.length > 1 ? parts : [];
91
+ }
92
+
93
+ /**
94
+ * Light stemmer: de-pluralisation plus a short suffix table.
95
+ *
96
+ * Not linguistically correct and not meant to be — index and query run through
97
+ * the same function, so what matters is that variants of one word collapse to
98
+ * one key ("paginated" and "pagination" both reach "paginat").
99
+ */
100
+ export function stem(word: string): string {
101
+ let result = word;
102
+
103
+ if (
104
+ result.length > 3 &&
105
+ result.endsWith("s") &&
106
+ !NO_STEM_SUFFIX.test(result)
107
+ ) {
108
+ result = result.endsWith("ies")
109
+ ? `${result.slice(0, -3)}y`
110
+ : result.endsWith("es") && result.length > 4
111
+ ? result.slice(0, -2)
112
+ : result.slice(0, -1);
113
+ }
114
+
115
+ for (const [pattern, replacement] of SUFFIX_RULES) {
116
+ if (!pattern.test(result)) continue;
117
+ const candidate = result.replace(pattern, replacement);
118
+ if (candidate.length >= MIN_STEM_LENGTH) return candidate;
119
+ break;
120
+ }
121
+
122
+ return result;
123
+ }
124
+
125
+ /**
126
+ * Lowercased, stemmed tokens. Identifiers also yield their sub-words, so a
127
+ * query for "list filters" matches a chunk that only mentions `MapoListFilters`.
128
+ */
129
+ export function tokenize(input: string): string[] {
130
+ const out: string[] = [];
131
+ const words = input.match(/[A-Za-z][A-Za-z0-9]*|[0-9]+/g) ?? [];
132
+
133
+ for (const word of words) {
134
+ const lower = word.toLowerCase();
135
+ if (lower.length < 2) continue;
136
+ if (!STOPWORDS.has(lower)) out.push(stem(lower));
137
+
138
+ for (const part of splitIdentifier(word)) {
139
+ const lowerPart = part.toLowerCase();
140
+ if (lowerPart.length < 2 || STOPWORDS.has(lowerPart)) continue;
141
+ out.push(stem(lowerPart));
142
+ }
143
+ }
144
+
145
+ return out;
146
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Transport-agnostic tool specs.
3
+ *
4
+ * One implementation, two adapters: the Nitro definitions under
5
+ * `runtime/mcp/handlers/mapo/tools/` wrap these with `defineMcpTool`, and the
6
+ * stdio CLI registers the very same specs on an SDK server. Tool behaviour can
7
+ * therefore never drift between "dev server running" and "dev server down".
8
+ */
9
+ import type { ZodRawShape } from "zod";
10
+ import type { MapoAppManifest } from "../../index.js";
11
+ import type { ApiKnowledge, DocsKnowledge } from "./types.js";
12
+
13
+ /** Everything a tool may need, provided lazily so unused sources are never read. */
14
+ export interface MapoToolContext {
15
+ /** Bundled docs index. Throws `KnowledgeNotBuiltError` when not generated. */
16
+ knowledge: () => DocsKnowledge;
17
+ /** Component, field and composable surface extracted from source. */
18
+ api: () => ApiKnowledge;
19
+ /**
20
+ * Snapshot of the app the server runs inside, or `null` when there is none —
21
+ * the stdio CLI knows the framework but not the project using it.
22
+ */
23
+ manifest: () => MapoAppManifest | null;
24
+ /**
25
+ * Absolute project root for scaffolding, or `null` when unknown. The Nuxt
26
+ * module reports `rootDir`; the CLI uses its working directory.
27
+ */
28
+ rootDir: () => string | null;
29
+ /** Whether files may be written at all: development only. */
30
+ canWrite: () => boolean;
31
+ /**
32
+ * Where to read the backend's OpenAPI schema, and the credential for it.
33
+ * The token is resolved per request from the environment, never baked into
34
+ * the build output.
35
+ */
36
+ backend: () => { schemaUrl: string | null; token: string | null };
37
+ }
38
+
39
+ export interface MapoToolAnnotations {
40
+ readOnlyHint?: boolean;
41
+ destructiveHint?: boolean;
42
+ idempotentHint?: boolean;
43
+ openWorldHint?: boolean;
44
+ }
45
+
46
+ /**
47
+ * `Args` is declared explicitly by each tool and must mirror `inputSchema`;
48
+ * the schema stays the single runtime source of truth (the MCP SDK validates
49
+ * against it before `run` is called).
50
+ */
51
+ export interface MapoToolSpec<
52
+ Args = Record<string, unknown>,
53
+ Shape extends ZodRawShape = ZodRawShape,
54
+ > {
55
+ /** Prefixed with `mapo_` so it stays unambiguous alongside other MCP servers. */
56
+ name: string;
57
+ title: string;
58
+ description: string;
59
+ inputSchema: Shape;
60
+ annotations?: MapoToolAnnotations;
61
+ inputExamples?: Array<Partial<Args>>;
62
+ /** Returns markdown — agents read it directly, no client-side parsing needed. */
63
+ run: (args: Args, context: MapoToolContext) => string | Promise<string>;
64
+ }
65
+
66
+ /** Tool slot for heterogeneous registries. */
67
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
+ export type AnyMapoToolSpec = MapoToolSpec<any, any>;
69
+
70
+ export function defineMapoTool<Args, Shape extends ZodRawShape>(
71
+ spec: MapoToolSpec<Args, Shape>,
72
+ ): MapoToolSpec<Args, Shape> {
73
+ return spec;
74
+ }