Skip to content

Commit 45cc3fe

Browse files
authored
fix(docsite): the MCP route's keyword index takes any doc keyword, constructor and __proto__ included (#9526)
fix(docsite): the MCP route's keyword index takes any doc keyword, constructor and __proto__ included The route built its keyword index as a plain object when it loads, so a doc keyword "constructor" or "__proto__" read a property the object inherits (Object, Object.prototype), and .includes on it threw: the route could not load, and next build stopped collecting /mcp. The doc schema takes any string as a keyword. The index is a Map now, built and read by keywordIndex.ts, which the route calls. The route's test imports those functions in place of its own copy, which could not see the route's bug, and a new test runs fixture docs with the keywords constructor, __proto__ and toString through them.
1 parent f9ac85f commit 45cc3fe

4 files changed

Lines changed: 122 additions & 78 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file mcp-keyword-index.test.ts
5+
* @input The MCP route's keyword index (app/mcp/keywordIndex.ts) and fixture
6+
* docs whose keywords include names that a plain object inherits
7+
* @output Checks that each keyword is its own entry and resolves to its
8+
* component
9+
* @position Docsite tests; run with `pnpm -F @astryxdesign/docsite test`
10+
*/
11+
12+
import {describe, expect, it} from 'vitest';
13+
import {buildKeywordIndex, resolveKeywords} from '../app/mcp/keywordIndex';
14+
15+
const docs = [
16+
{name: 'Builder', keywords: ['constructor', 'factory']},
17+
{name: 'Prototype', keywords: ['__proto__']},
18+
{name: 'Printer', keywords: ['toString', 'factory']},
19+
];
20+
21+
describe('MCP keyword index over keywords a plain object inherits', () => {
22+
it('indexes each keyword as its own entry', () => {
23+
const index = buildKeywordIndex(docs);
24+
expect(index.get('constructor')).toEqual(['Builder']);
25+
expect(index.get('__proto__')).toEqual(['Prototype']);
26+
expect(index.get('tostring')).toEqual(['Printer']);
27+
expect(index.get('factory')).toEqual(['Builder', 'Printer']);
28+
expect(index.get('valueof')).toBeUndefined();
29+
});
30+
31+
it('resolves a query that names one of them to its component', () => {
32+
const index = buildKeywordIndex(docs);
33+
expect(resolveKeywords(index, 'Constructor')).toEqual(['Builder']);
34+
expect(resolveKeywords(index, '__proto__')).toEqual(['Prototype']);
35+
expect(resolveKeywords(index, 'a factory')).toEqual(['Builder', 'Printer']);
36+
expect(resolveKeywords(index, 'hasOwnProperty')).toEqual([]);
37+
});
38+
});

‎apps/docsite/src/__tests__/mcp-server.test.ts‎

Lines changed: 24 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
* @file MCP server tests.
55
*
66
* Validates the keyword-based search resolution and branding for the
7-
* MCP server route handler. Uses the same generated registries as the
8-
* actual server.
7+
* MCP server route handler. Uses the same generated registries and keyword
8+
* index as the actual server.
99
*
1010
* Run: pnpm -F @astryxdesign/docsite test
1111
*/
@@ -21,42 +21,18 @@ import {
2121
} from '../../../../packages/cli/foundation/discovery/template-adapter.mjs';
2222

2323
import type {ComponentEntry} from '../generated/componentRegistry';
24+
import {buildKeywordIndex, resolveKeywords} from '../app/mcp/keywordIndex';
2425

2526
// ── Replicate MCP server logic for testing ─────────────────────────────
26-
// These mirror the runtime logic in apps/docsite/src/app/mcp/route.ts
27-
// without importing the Next.js route handler directly.
27+
// The keyword index and its resolution are the route's own (keywordIndex.ts).
28+
// The scoring below mirrors the runtime logic in
29+
// apps/docsite/src/app/mcp/route.ts without importing the Next.js route
30+
// handler directly.
2831

2932
const allComponents: ComponentEntry[] = Object.values(components).flat();
3033
const visibleComponents = allComponents.filter(c => !c.hidden);
3134

32-
function buildKeywordIndex(): Record<string, string[]> {
33-
const index: Record<string, string[]> = {};
34-
for (const comp of visibleComponents) {
35-
for (const kw of comp.keywords) {
36-
const lower = kw.toLowerCase();
37-
if (!index[lower]) {
38-
index[lower] = [];
39-
}
40-
if (!index[lower].includes(comp.name)) {
41-
index[lower].push(comp.name);
42-
}
43-
}
44-
}
45-
return index;
46-
}
47-
48-
const keywordIndex = buildKeywordIndex();
49-
50-
function resolveKeywords(query: string): string[] {
51-
const lower = query.toLowerCase();
52-
const resolved: string[] = [];
53-
for (const [keyword, componentNames] of Object.entries(keywordIndex)) {
54-
if (lower.includes(keyword) || keyword.includes(lower)) {
55-
resolved.push(...componentNames);
56-
}
57-
}
58-
return [...new Set(resolved)];
59-
}
35+
const keywordIndex = buildKeywordIndex(visibleComponents);
6036

6137
function score(text: string, query: string): number {
6238
const lower = text.toLowerCase();
@@ -94,7 +70,7 @@ function score(text: string, query: string): number {
9470
}
9571

9672
function simulateSearch(query: string, limit = 8) {
97-
const keywordMatches = resolveKeywords(query);
73+
const keywordMatches = resolveKeywords(keywordIndex, query);
9874
const scored: Array<{name: string; score: number; type: string}> = [];
9975

10076
for (const comp of visibleComponents) {
@@ -142,34 +118,33 @@ function simulateSearch(query: string, limit = 8) {
142118

143119
describe('MCP keyword index', () => {
144120
it('builds a non-empty keyword index from component docs', () => {
145-
const keys = Object.keys(keywordIndex);
146-
expect(keys.length).toBeGreaterThan(50);
121+
expect(keywordIndex.size).toBeGreaterThan(50);
147122
});
148123

149124
it('Toast is indexed under "snackbar"', () => {
150-
expect(keywordIndex['snackbar']).toBeDefined();
151-
expect(keywordIndex['snackbar']).toContain('Toast');
125+
expect(keywordIndex.get('snackbar')).toBeDefined();
126+
expect(keywordIndex.get('snackbar')).toContain('Toast');
152127
});
153128

154129
it('Selector is indexed under "dropdown"', () => {
155-
expect(keywordIndex['dropdown']).toBeDefined();
156-
expect(keywordIndex['dropdown']).toContain('Selector');
130+
expect(keywordIndex.get('dropdown')).toBeDefined();
131+
expect(keywordIndex.get('dropdown')).toContain('Selector');
157132
});
158133

159134
it('Dialog is indexed under "modal"', () => {
160-
expect(keywordIndex['modal']).toBeDefined();
161-
expect(keywordIndex['modal']).toContain('Dialog');
135+
expect(keywordIndex.get('modal')).toBeDefined();
136+
expect(keywordIndex.get('modal')).toContain('Dialog');
162137
});
163138

164139
it('no duplicate component names within a keyword entry', () => {
165-
for (const [, names] of Object.entries(keywordIndex)) {
140+
for (const names of keywordIndex.values()) {
166141
expect(new Set(names).size).toBe(names.length);
167142
}
168143
});
169144

170145
it('hidden components are excluded from the index', () => {
171146
const hiddenNames = allComponents.filter(c => c.hidden).map(c => c.name);
172-
const indexedNames = new Set(Object.values(keywordIndex).flat());
147+
const indexedNames = new Set([...keywordIndex.values()].flat());
173148
for (const name of hiddenNames) {
174149
expect(indexedNames.has(name)).toBe(false);
175150
}
@@ -178,33 +153,33 @@ describe('MCP keyword index', () => {
178153

179154
describe('MCP keyword resolution', () => {
180155
it('resolves "snackbar" to Toast', () => {
181-
const results = resolveKeywords('snackbar');
156+
const results = resolveKeywords(keywordIndex, 'snackbar');
182157
expect(results).toContain('Toast');
183158
});
184159

185160
it('resolves "dropdown" to Selector', () => {
186-
const results = resolveKeywords('dropdown');
161+
const results = resolveKeywords(keywordIndex, 'dropdown');
187162
expect(results).toContain('Selector');
188163
});
189164

190165
it('resolves "modal" to Dialog', () => {
191-
const results = resolveKeywords('modal');
166+
const results = resolveKeywords(keywordIndex, 'modal');
192167
expect(results).toContain('Dialog');
193168
});
194169

195170
it('resolves multi-word queries by substring matching', () => {
196-
const results = resolveKeywords('toast notification');
171+
const results = resolveKeywords(keywordIndex, 'toast notification');
197172
expect(results).toContain('Toast');
198173
});
199174

200175
it('returns empty for nonsense queries', () => {
201-
const results = resolveKeywords('xyzzy12345');
176+
const results = resolveKeywords(keywordIndex, 'xyzzy12345');
202177
expect(results).toEqual([]);
203178
});
204179

205180
it('deduplicates results', () => {
206181
// A query that matches multiple keywords for the same component
207-
const results = resolveKeywords('select dropdown');
182+
const results = resolveKeywords(keywordIndex, 'select dropdown');
208183
const selectorCount = results.filter(r => r === 'Selector').length;
209184
expect(selectorCount).toBeLessThanOrEqual(1);
210185
});
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file keywordIndex.ts
5+
* @input Each visible component's name and its `.doc.mjs` keywords
6+
* @output buildKeywordIndex (each lowercased keyword to the components that
7+
* list it) and resolveKeywords (the components whose keywords a query names)
8+
* @position The MCP route's keyword resolution; its tests import it too
9+
*
10+
* A doc keyword is any string. The index is a Map because a plain object
11+
* reads a keyword such as `constructor` or `__proto__` as a property it
12+
* inherits, and the route then fails as it loads.
13+
*/
14+
15+
/** What the index reads from a component's doc. */
16+
export interface KeywordSource {
17+
readonly name: string;
18+
readonly keywords: ReadonlyArray<string>;
19+
}
20+
21+
/** Each lowercased keyword, with the components that list it, in doc order. */
22+
export function buildKeywordIndex(
23+
sources: ReadonlyArray<KeywordSource>,
24+
): ReadonlyMap<string, ReadonlyArray<string>> {
25+
const index = new Map<string, string[]>();
26+
for (const source of sources) {
27+
for (const keyword of source.keywords) {
28+
const lower = keyword.toLowerCase();
29+
const names = index.get(lower);
30+
if (names == null) {
31+
index.set(lower, [source.name]);
32+
} else if (!names.includes(source.name)) {
33+
names.push(source.name);
34+
}
35+
}
36+
}
37+
return index;
38+
}
39+
40+
/**
41+
* The components with a keyword the query contains or that contains the
42+
* query, each once.
43+
*/
44+
export function resolveKeywords(
45+
index: ReadonlyMap<string, ReadonlyArray<string>>,
46+
query: string,
47+
): string[] {
48+
const lower = query.toLowerCase();
49+
const resolved: string[] = [];
50+
for (const [keyword, names] of index) {
51+
if (lower.includes(keyword) || keyword.includes(lower)) {
52+
resolved.push(...names);
53+
}
54+
}
55+
return [...new Set(resolved)];
56+
}

‎apps/docsite/src/app/mcp/route.ts‎

Lines changed: 4 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {components} from '../../generated/componentRegistry';
2222
import {docTopics} from '../../generated/docsRegistry';
2323
import {blocks} from '../../generated/blockRegistry';
2424
import {templates} from '../../generated/templateRegistry';
25+
import {buildKeywordIndex, resolveKeywords} from './keywordIndex';
2526

2627
import type {ComponentEntry} from '../../generated/componentRegistry';
2728
import type {DocTopic} from '../../generated/docsRegistry';
@@ -46,18 +47,7 @@ function componentInstall(comp: ComponentEntry): string {
4647
// Built from the `keywords` field on each component's .doc.mjs file.
4748
// Inverts keyword[] → component name so natural language queries resolve
4849
// to the right components without a hardcoded alias map.
49-
const keywordIndex: Record<string, string[]> = {};
50-
for (const comp of visibleComponents) {
51-
for (const kw of comp.keywords) {
52-
const lower = kw.toLowerCase();
53-
if (!keywordIndex[lower]) {
54-
keywordIndex[lower] = [];
55-
}
56-
if (!keywordIndex[lower].includes(comp.name)) {
57-
keywordIndex[lower].push(comp.name);
58-
}
59-
}
60-
}
50+
const keywordIndex = buildKeywordIndex(visibleComponents);
6151

6252
// ── Scoring ────────────────────────────────────────────────────────────
6353

@@ -100,21 +90,6 @@ function score(text: string, query: string): number {
10090
return 0;
10191
}
10292

103-
/** Resolve keywords from component docs to boost matching components */
104-
function resolveKeywords(query: string): string[] {
105-
const lower = query.toLowerCase();
106-
const resolved: string[] = [];
107-
108-
// Check each keyword in the index
109-
for (const [keyword, componentNames] of Object.entries(keywordIndex)) {
110-
if (lower.includes(keyword) || keyword.includes(lower)) {
111-
resolved.push(...componentNames);
112-
}
113-
}
114-
115-
return [...new Set(resolved)];
116-
}
117-
11893
// ── Context Budget ─────────────────────────────────────────────────────
11994
const MAX_TOPIC_BRIEF_CHARS = 4000;
12095

@@ -135,7 +110,7 @@ const handler = createMcpHandler(
135110
limit: z.number().optional().describe('Max results (default 8).'),
136111
},
137112
async ({query, limit = 8}) => {
138-
const keywordMatches = resolveKeywords(query);
113+
const keywordMatches = resolveKeywords(keywordIndex, query);
139114

140115
const scored: Array<{
141116
item: ComponentEntry | DocTopic | TemplateEntry;
@@ -530,7 +505,7 @@ const handler = createMcpHandler(
530505
}
531506

532507
// ── Fuzzy fallback with keyword awareness ──────────────────────
533-
const keywordResolved = resolveKeywords(name);
508+
const keywordResolved = resolveKeywords(keywordIndex, name);
534509
const keywordComponents =
535510
keywordResolved.length > 0
536511
? visibleComponents

0 commit comments

Comments
 (0)