Skip to content

Commit 8def340

Browse files
chore(internal): improve local docs search for MCP servers
1 parent 9908707 commit 8def340

File tree

2 files changed

+64
-22
lines changed

2 files changed

+64
-22
lines changed

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 = {
@@ -371,6 +377,8 @@ const EMBEDDED_METHODS: MethodEntry[] = [
371377
},
372378
];
373379

380+
const EMBEDDED_READMES: { language: string; content: string }[] = [];
381+
374382
const INDEX_OPTIONS = {
375383
fields: [
376384
'name',
@@ -385,13 +393,15 @@ const INDEX_OPTIONS = {
385393
storeFields: ['kind', '_original'],
386394
searchOptions: {
387395
prefix: true,
388-
fuzzy: 0.2,
396+
fuzzy: 0.1,
389397
boost: {
390-
name: 3,
391-
endpoint: 2,
398+
name: 5,
399+
stainlessPath: 3,
400+
endpoint: 3,
401+
qualified: 3,
392402
summary: 2,
393-
qualified: 2,
394403
content: 1,
404+
description: 1,
395405
} as Record<string, number>,
396406
},
397407
};
@@ -413,30 +423,45 @@ export class LocalDocsSearch {
413423
static async create(opts?: { docsDir?: string }): Promise<LocalDocsSearch> {
414424
const instance = new LocalDocsSearch();
415425
instance.indexMethods(EMBEDDED_METHODS);
426+
for (const readme of EMBEDDED_READMES) {
427+
instance.indexProse(readme.content, `readme:${readme.language}`);
428+
}
416429
if (opts?.docsDir) {
417430
await instance.loadDocsDirectory(opts.docsDir);
418431
}
419432
return instance;
420433
}
421434

422-
// Note: Language is accepted for interface consistency with remote search, but currently has no
423-
// effect since this local search only supports TypeScript docs.
424435
search(props: {
425436
query: string;
426437
language?: string;
427438
detail?: string;
428439
maxResults?: number;
429440
maxLength?: number;
430441
}): SearchResult {
431-
const { query, detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
442+
const { query, language = 'typescript', detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
432443

433444
const useMarkdown = detail === 'verbose' || detail === 'high';
434445

435-
// Search both indices and merge results by score
446+
// Search both indices and merge results by score.
447+
// Filter prose hits so language-tagged content (READMEs and docs with
448+
// frontmatter) only matches the requested language.
436449
const methodHits = this.methodIndex
437450
.search(query)
438451
.map((hit) => ({ ...hit, _kind: 'http_method' as const }));
439-
const proseHits = this.proseIndex.search(query).map((hit) => ({ ...hit, _kind: 'prose' as const }));
452+
const proseHits = this.proseIndex
453+
.search(query)
454+
.filter((hit) => {
455+
const source = ((hit as Record<string, unknown>)['_original'] as ProseChunk | undefined)?.source;
456+
if (!source) return true;
457+
// Check for language-tagged sources: "readme:<lang>" or "lang:<lang>:<filename>"
458+
let taggedLang: string | undefined;
459+
if (source.startsWith('readme:')) taggedLang = source.slice('readme:'.length);
460+
else if (source.startsWith('lang:')) taggedLang = source.split(':')[1];
461+
if (!taggedLang) return true;
462+
return taggedLang === language || (language === 'javascript' && taggedLang === 'typescript');
463+
})
464+
.map((hit) => ({ ...hit, _kind: 'prose' as const }));
440465
const merged = [...methodHits, ...proseHits].sort((a, b) => b.score - a.score);
441466
const top = merged.slice(0, maxResults);
442467

@@ -449,11 +474,16 @@ export class LocalDocsSearch {
449474
if (useMarkdown && m.markdown) {
450475
fullResults.push(m.markdown);
451476
} else {
477+
// Use per-language data when available, falling back to the
478+
// top-level fields (which are TypeScript-specific in the
479+
// legacy codepath).
480+
const langData = m.perLanguage?.[language];
452481
fullResults.push({
453-
method: m.qualified,
482+
method: langData?.method ?? m.qualified,
454483
summary: m.summary,
455484
description: m.description,
456485
endpoint: `${m.httpMethod.toUpperCase()} ${m.endpoint}`,
486+
...(langData?.example ? { example: langData.example } : {}),
457487
...(m.params ? { params: m.params } : {}),
458488
...(m.response ? { response: m.response } : {}),
459489
});
@@ -524,7 +554,19 @@ export class LocalDocsSearch {
524554
this.indexProse(texts.join('\n\n'), file.name);
525555
}
526556
} else {
527-
this.indexProse(content, file.name);
557+
// Parse optional YAML frontmatter for language tagging.
558+
// Files with a "language" field in frontmatter will only
559+
// surface in searches for that language.
560+
//
561+
// Example:
562+
// ---
563+
// language: python
564+
// ---
565+
// # Error handling in Python
566+
// ...
567+
const frontmatter = parseFrontmatter(content);
568+
const source = frontmatter.language ? `lang:${frontmatter.language}:${file.name}` : file.name;
569+
this.indexProse(content, source);
528570
}
529571
} catch (err) {
530572
getLogger().warn({ err, file: file.name }, 'Failed to index docs file');
@@ -602,3 +644,12 @@ function extractTexts(data: unknown, depth = 0): string[] {
602644
}
603645
return [];
604646
}
647+
648+
/** Parses YAML frontmatter from a markdown string, extracting the language field if present. */
649+
function parseFrontmatter(markdown: string): { language?: string } {
650+
const match = markdown.match(/^---\n([\s\S]*?)\n---/);
651+
if (!match) return {};
652+
const body = match[1] ?? '';
653+
const langMatch = body.match(/^language:\s*(.+)$/m);
654+
return langMatch ? { language: langMatch[1]!.trim() } : {};
655+
}

0 commit comments

Comments
 (0)