Skip to content

Commit 6c0fe3f

Browse files
chore(internal): improve local docs search for MCP servers
1 parent bb8cffe commit 6c0fe3f

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 = {
@@ -381,6 +387,8 @@ const EMBEDDED_METHODS: MethodEntry[] = [
381387
},
382388
];
383389

390+
const EMBEDDED_READMES: { language: string; content: string }[] = [];
391+
384392
const INDEX_OPTIONS = {
385393
fields: [
386394
'name',
@@ -395,13 +403,15 @@ const INDEX_OPTIONS = {
395403
storeFields: ['kind', '_original'],
396404
searchOptions: {
397405
prefix: true,
398-
fuzzy: 0.2,
406+
fuzzy: 0.1,
399407
boost: {
400-
name: 3,
401-
endpoint: 2,
408+
name: 5,
409+
stainlessPath: 3,
410+
endpoint: 3,
411+
qualified: 3,
402412
summary: 2,
403-
qualified: 2,
404413
content: 1,
414+
description: 1,
405415
} as Record<string, number>,
406416
},
407417
};
@@ -423,30 +433,45 @@ export class LocalDocsSearch {
423433
static async create(opts?: { docsDir?: string }): Promise<LocalDocsSearch> {
424434
const instance = new LocalDocsSearch();
425435
instance.indexMethods(EMBEDDED_METHODS);
436+
for (const readme of EMBEDDED_READMES) {
437+
instance.indexProse(readme.content, `readme:${readme.language}`);
438+
}
426439
if (opts?.docsDir) {
427440
await instance.loadDocsDirectory(opts.docsDir);
428441
}
429442
return instance;
430443
}
431444

432-
// Note: Language is accepted for interface consistency with remote search, but currently has no
433-
// effect since this local search only supports TypeScript docs.
434445
search(props: {
435446
query: string;
436447
language?: string;
437448
detail?: string;
438449
maxResults?: number;
439450
maxLength?: number;
440451
}): SearchResult {
441-
const { query, detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
452+
const { query, language = 'typescript', detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
442453

443454
const useMarkdown = detail === 'verbose' || detail === 'high';
444455

445-
// Search both indices and merge results by score
456+
// Search both indices and merge results by score.
457+
// Filter prose hits so language-tagged content (READMEs and docs with
458+
// frontmatter) only matches the requested language.
446459
const methodHits = this.methodIndex
447460
.search(query)
448461
.map((hit) => ({ ...hit, _kind: 'http_method' as const }));
449-
const proseHits = this.proseIndex.search(query).map((hit) => ({ ...hit, _kind: 'prose' as const }));
462+
const proseHits = this.proseIndex
463+
.search(query)
464+
.filter((hit) => {
465+
const source = ((hit as Record<string, unknown>)['_original'] as ProseChunk | undefined)?.source;
466+
if (!source) return true;
467+
// Check for language-tagged sources: "readme:<lang>" or "lang:<lang>:<filename>"
468+
let taggedLang: string | undefined;
469+
if (source.startsWith('readme:')) taggedLang = source.slice('readme:'.length);
470+
else if (source.startsWith('lang:')) taggedLang = source.split(':')[1];
471+
if (!taggedLang) return true;
472+
return taggedLang === language || (language === 'javascript' && taggedLang === 'typescript');
473+
})
474+
.map((hit) => ({ ...hit, _kind: 'prose' as const }));
450475
const merged = [...methodHits, ...proseHits].sort((a, b) => b.score - a.score);
451476
const top = merged.slice(0, maxResults);
452477

@@ -459,11 +484,16 @@ export class LocalDocsSearch {
459484
if (useMarkdown && m.markdown) {
460485
fullResults.push(m.markdown);
461486
} else {
487+
// Use per-language data when available, falling back to the
488+
// top-level fields (which are TypeScript-specific in the
489+
// legacy codepath).
490+
const langData = m.perLanguage?.[language];
462491
fullResults.push({
463-
method: m.qualified,
492+
method: langData?.method ?? m.qualified,
464493
summary: m.summary,
465494
description: m.description,
466495
endpoint: `${m.httpMethod.toUpperCase()} ${m.endpoint}`,
496+
...(langData?.example ? { example: langData.example } : {}),
467497
...(m.params ? { params: m.params } : {}),
468498
...(m.response ? { response: m.response } : {}),
469499
});
@@ -534,7 +564,19 @@ export class LocalDocsSearch {
534564
this.indexProse(texts.join('\n\n'), file.name);
535565
}
536566
} else {
537-
this.indexProse(content, file.name);
567+
// Parse optional YAML frontmatter for language tagging.
568+
// Files with a "language" field in frontmatter will only
569+
// surface in searches for that language.
570+
//
571+
// Example:
572+
// ---
573+
// language: python
574+
// ---
575+
// # Error handling in Python
576+
// ...
577+
const frontmatter = parseFrontmatter(content);
578+
const source = frontmatter.language ? `lang:${frontmatter.language}:${file.name}` : file.name;
579+
this.indexProse(content, source);
538580
}
539581
} catch (err) {
540582
getLogger().warn({ err, file: file.name }, 'Failed to index docs file');
@@ -612,3 +654,12 @@ function extractTexts(data: unknown, depth = 0): string[] {
612654
}
613655
return [];
614656
}
657+
658+
/** Parses YAML frontmatter from a markdown string, extracting the language field if present. */
659+
function parseFrontmatter(markdown: string): { language?: string } {
660+
const match = markdown.match(/^---\n([\s\S]*?)\n---/);
661+
if (!match) return {};
662+
const body = match[1] ?? '';
663+
const langMatch = body.match(/^language:\s*(.+)$/m);
664+
return langMatch ? { language: langMatch[1]!.trim() } : {};
665+
}

0 commit comments

Comments
 (0)