Skip to content

Commit 04d3e6d

Browse files
chore(internal): improve local docs search for MCP servers
1 parent 113e23c commit 04d3e6d

2 files changed

Lines changed: 64 additions & 22 deletions

File tree

packages/mcp-server/src/docs-search-tool.ts

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,29 +50,20 @@ export function setLocalSearch(search: LocalDocsSearch): void {
5050
_localSearch = search;
5151
}
5252

53-
const SUPPORTED_LANGUAGES = new Set(['http', 'typescript', 'javascript']);
54-
5553
async function searchLocal(args: Record<string, unknown>): Promise<unknown> {
5654
if (!_localSearch) {
5755
throw new Error('Local search not initialized');
5856
}
5957

6058
const query = (args['query'] as string) ?? '';
6159
const language = (args['language'] as string) ?? 'typescript';
62-
const detail = (args['detail'] as string) ?? 'verbose';
63-
64-
if (!SUPPORTED_LANGUAGES.has(language)) {
65-
throw new Error(
66-
`Local docs search only supports HTTP, TypeScript, and JavaScript. Got language="${language}". ` +
67-
`Use --docs-search-mode stainless-api for other languages, or set language to "http", "typescript", or "javascript".`,
68-
);
69-
}
60+
const detail = (args['detail'] as string) ?? 'default';
7061

7162
return _localSearch.search({
7263
query,
7364
language,
7465
detail,
75-
maxResults: 10,
66+
maxResults: 5,
7667
}).results;
7768
}
7869

packages/mcp-server/src/local-docs-search.ts

Lines changed: 62 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ import * as fs from 'node:fs/promises';
55
import * as path from 'node:path';
66
import { getLogger } from './logger';
77

8+
type PerLanguageData = {
9+
method?: string;
10+
example?: string;
11+
};
12+
813
type MethodEntry = {
914
name: string;
1015
endpoint: string;
@@ -16,6 +21,7 @@ type MethodEntry = {
1621
params?: string[];
1722
response?: string;
1823
markdown?: string;
24+
perLanguage?: Record<string, PerLanguageData>;
1925
};
2026

2127
type ProseChunk = {
@@ -145,6 +151,8 @@ const EMBEDDED_METHODS: MethodEntry[] = [
145151
},
146152
];
147153

154+
const EMBEDDED_READMES: { language: string; content: string }[] = [];
155+
148156
const INDEX_OPTIONS = {
149157
fields: [
150158
'name',
@@ -159,13 +167,15 @@ const INDEX_OPTIONS = {
159167
storeFields: ['kind', '_original'],
160168
searchOptions: {
161169
prefix: true,
162-
fuzzy: 0.2,
170+
fuzzy: 0.1,
163171
boost: {
164-
name: 3,
165-
endpoint: 2,
172+
name: 5,
173+
stainlessPath: 3,
174+
endpoint: 3,
175+
qualified: 3,
166176
summary: 2,
167-
qualified: 2,
168177
content: 1,
178+
description: 1,
169179
} as Record<string, number>,
170180
},
171181
};
@@ -187,30 +197,45 @@ export class LocalDocsSearch {
187197
static async create(opts?: { docsDir?: string }): Promise<LocalDocsSearch> {
188198
const instance = new LocalDocsSearch();
189199
instance.indexMethods(EMBEDDED_METHODS);
200+
for (const readme of EMBEDDED_READMES) {
201+
instance.indexProse(readme.content, `readme:${readme.language}`);
202+
}
190203
if (opts?.docsDir) {
191204
await instance.loadDocsDirectory(opts.docsDir);
192205
}
193206
return instance;
194207
}
195208

196-
// Note: Language is accepted for interface consistency with remote search, but currently has no
197-
// effect since this local search only supports TypeScript docs.
198209
search(props: {
199210
query: string;
200211
language?: string;
201212
detail?: string;
202213
maxResults?: number;
203214
maxLength?: number;
204215
}): SearchResult {
205-
const { query, detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
216+
const { query, language = 'typescript', detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
206217

207218
const useMarkdown = detail === 'verbose' || detail === 'high';
208219

209-
// Search both indices and merge results by score
220+
// Search both indices and merge results by score.
221+
// Filter prose hits so language-tagged content (READMEs and docs with
222+
// frontmatter) only matches the requested language.
210223
const methodHits = this.methodIndex
211224
.search(query)
212225
.map((hit) => ({ ...hit, _kind: 'http_method' as const }));
213-
const proseHits = this.proseIndex.search(query).map((hit) => ({ ...hit, _kind: 'prose' as const }));
226+
const proseHits = this.proseIndex
227+
.search(query)
228+
.filter((hit) => {
229+
const source = ((hit as Record<string, unknown>)['_original'] as ProseChunk | undefined)?.source;
230+
if (!source) return true;
231+
// Check for language-tagged sources: "readme:<lang>" or "lang:<lang>:<filename>"
232+
let taggedLang: string | undefined;
233+
if (source.startsWith('readme:')) taggedLang = source.slice('readme:'.length);
234+
else if (source.startsWith('lang:')) taggedLang = source.split(':')[1];
235+
if (!taggedLang) return true;
236+
return taggedLang === language || (language === 'javascript' && taggedLang === 'typescript');
237+
})
238+
.map((hit) => ({ ...hit, _kind: 'prose' as const }));
214239
const merged = [...methodHits, ...proseHits].sort((a, b) => b.score - a.score);
215240
const top = merged.slice(0, maxResults);
216241

@@ -223,11 +248,16 @@ export class LocalDocsSearch {
223248
if (useMarkdown && m.markdown) {
224249
fullResults.push(m.markdown);
225250
} else {
251+
// Use per-language data when available, falling back to the
252+
// top-level fields (which are TypeScript-specific in the
253+
// legacy codepath).
254+
const langData = m.perLanguage?.[language];
226255
fullResults.push({
227-
method: m.qualified,
256+
method: langData?.method ?? m.qualified,
228257
summary: m.summary,
229258
description: m.description,
230259
endpoint: `${m.httpMethod.toUpperCase()} ${m.endpoint}`,
260+
...(langData?.example ? { example: langData.example } : {}),
231261
...(m.params ? { params: m.params } : {}),
232262
...(m.response ? { response: m.response } : {}),
233263
});
@@ -298,7 +328,19 @@ export class LocalDocsSearch {
298328
this.indexProse(texts.join('\n\n'), file.name);
299329
}
300330
} else {
301-
this.indexProse(content, file.name);
331+
// Parse optional YAML frontmatter for language tagging.
332+
// Files with a "language" field in frontmatter will only
333+
// surface in searches for that language.
334+
//
335+
// Example:
336+
// ---
337+
// language: python
338+
// ---
339+
// # Error handling in Python
340+
// ...
341+
const frontmatter = parseFrontmatter(content);
342+
const source = frontmatter.language ? `lang:${frontmatter.language}:${file.name}` : file.name;
343+
this.indexProse(content, source);
302344
}
303345
} catch (err) {
304346
getLogger().warn({ err, file: file.name }, 'Failed to index docs file');
@@ -376,3 +418,12 @@ function extractTexts(data: unknown, depth = 0): string[] {
376418
}
377419
return [];
378420
}
421+
422+
/** Parses YAML frontmatter from a markdown string, extracting the language field if present. */
423+
function parseFrontmatter(markdown: string): { language?: string } {
424+
const match = markdown.match(/^---\n([\s\S]*?)\n---/);
425+
if (!match) return {};
426+
const body = match[1] ?? '';
427+
const langMatch = body.match(/^language:\s*(.+)$/m);
428+
return langMatch ? { language: langMatch[1]!.trim() } : {};
429+
}

0 commit comments

Comments
 (0)