Skip to content

Commit 211fb8f

Browse files
chore(internal): improve local docs search for MCP servers
1 parent f106d8b commit 211fb8f

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 = {
@@ -804,6 +810,8 @@ const EMBEDDED_METHODS: MethodEntry[] = [
804810
},
805811
];
806812

813+
const EMBEDDED_READMES: { language: string; content: string }[] = [];
814+
807815
const INDEX_OPTIONS = {
808816
fields: [
809817
'name',
@@ -818,13 +826,15 @@ const INDEX_OPTIONS = {
818826
storeFields: ['kind', '_original'],
819827
searchOptions: {
820828
prefix: true,
821-
fuzzy: 0.2,
829+
fuzzy: 0.1,
822830
boost: {
823-
name: 3,
824-
endpoint: 2,
831+
name: 5,
832+
stainlessPath: 3,
833+
endpoint: 3,
834+
qualified: 3,
825835
summary: 2,
826-
qualified: 2,
827836
content: 1,
837+
description: 1,
828838
} as Record<string, number>,
829839
},
830840
};
@@ -846,30 +856,45 @@ export class LocalDocsSearch {
846856
static async create(opts?: { docsDir?: string }): Promise<LocalDocsSearch> {
847857
const instance = new LocalDocsSearch();
848858
instance.indexMethods(EMBEDDED_METHODS);
859+
for (const readme of EMBEDDED_READMES) {
860+
instance.indexProse(readme.content, `readme:${readme.language}`);
861+
}
849862
if (opts?.docsDir) {
850863
await instance.loadDocsDirectory(opts.docsDir);
851864
}
852865
return instance;
853866
}
854867

855-
// Note: Language is accepted for interface consistency with remote search, but currently has no
856-
// effect since this local search only supports TypeScript docs.
857868
search(props: {
858869
query: string;
859870
language?: string;
860871
detail?: string;
861872
maxResults?: number;
862873
maxLength?: number;
863874
}): SearchResult {
864-
const { query, detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
875+
const { query, language = 'typescript', detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
865876

866877
const useMarkdown = detail === 'verbose' || detail === 'high';
867878

868-
// Search both indices and merge results by score
879+
// Search both indices and merge results by score.
880+
// Filter prose hits so language-tagged content (READMEs and docs with
881+
// frontmatter) only matches the requested language.
869882
const methodHits = this.methodIndex
870883
.search(query)
871884
.map((hit) => ({ ...hit, _kind: 'http_method' as const }));
872-
const proseHits = this.proseIndex.search(query).map((hit) => ({ ...hit, _kind: 'prose' as const }));
885+
const proseHits = this.proseIndex
886+
.search(query)
887+
.filter((hit) => {
888+
const source = ((hit as Record<string, unknown>)['_original'] as ProseChunk | undefined)?.source;
889+
if (!source) return true;
890+
// Check for language-tagged sources: "readme:<lang>" or "lang:<lang>:<filename>"
891+
let taggedLang: string | undefined;
892+
if (source.startsWith('readme:')) taggedLang = source.slice('readme:'.length);
893+
else if (source.startsWith('lang:')) taggedLang = source.split(':')[1];
894+
if (!taggedLang) return true;
895+
return taggedLang === language || (language === 'javascript' && taggedLang === 'typescript');
896+
})
897+
.map((hit) => ({ ...hit, _kind: 'prose' as const }));
873898
const merged = [...methodHits, ...proseHits].sort((a, b) => b.score - a.score);
874899
const top = merged.slice(0, maxResults);
875900

@@ -882,11 +907,16 @@ export class LocalDocsSearch {
882907
if (useMarkdown && m.markdown) {
883908
fullResults.push(m.markdown);
884909
} else {
910+
// Use per-language data when available, falling back to the
911+
// top-level fields (which are TypeScript-specific in the
912+
// legacy codepath).
913+
const langData = m.perLanguage?.[language];
885914
fullResults.push({
886-
method: m.qualified,
915+
method: langData?.method ?? m.qualified,
887916
summary: m.summary,
888917
description: m.description,
889918
endpoint: `${m.httpMethod.toUpperCase()} ${m.endpoint}`,
919+
...(langData?.example ? { example: langData.example } : {}),
890920
...(m.params ? { params: m.params } : {}),
891921
...(m.response ? { response: m.response } : {}),
892922
});
@@ -957,7 +987,19 @@ export class LocalDocsSearch {
957987
this.indexProse(texts.join('\n\n'), file.name);
958988
}
959989
} else {
960-
this.indexProse(content, file.name);
990+
// Parse optional YAML frontmatter for language tagging.
991+
// Files with a "language" field in frontmatter will only
992+
// surface in searches for that language.
993+
//
994+
// Example:
995+
// ---
996+
// language: python
997+
// ---
998+
// # Error handling in Python
999+
// ...
1000+
const frontmatter = parseFrontmatter(content);
1001+
const source = frontmatter.language ? `lang:${frontmatter.language}:${file.name}` : file.name;
1002+
this.indexProse(content, source);
9611003
}
9621004
} catch (err) {
9631005
getLogger().warn({ err, file: file.name }, 'Failed to index docs file');
@@ -1035,3 +1077,12 @@ function extractTexts(data: unknown, depth = 0): string[] {
10351077
}
10361078
return [];
10371079
}
1080+
1081+
/** Parses YAML frontmatter from a markdown string, extracting the language field if present. */
1082+
function parseFrontmatter(markdown: string): { language?: string } {
1083+
const match = markdown.match(/^---\n([\s\S]*?)\n---/);
1084+
if (!match) return {};
1085+
const body = match[1] ?? '';
1086+
const langMatch = body.match(/^language:\s*(.+)$/m);
1087+
return langMatch ? { language: langMatch[1]!.trim() } : {};
1088+
}

0 commit comments

Comments
 (0)