Skip to content

Commit d4db198

Browse files
chore(internal): improve local docs search for MCP servers
1 parent 36ec509 commit d4db198

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 = {
@@ -794,6 +800,8 @@ const EMBEDDED_METHODS: MethodEntry[] = [
794800
},
795801
];
796802

803+
const EMBEDDED_READMES: { language: string; content: string }[] = [];
804+
797805
const INDEX_OPTIONS = {
798806
fields: [
799807
'name',
@@ -808,13 +816,15 @@ const INDEX_OPTIONS = {
808816
storeFields: ['kind', '_original'],
809817
searchOptions: {
810818
prefix: true,
811-
fuzzy: 0.2,
819+
fuzzy: 0.1,
812820
boost: {
813-
name: 3,
814-
endpoint: 2,
821+
name: 5,
822+
stainlessPath: 3,
823+
endpoint: 3,
824+
qualified: 3,
815825
summary: 2,
816-
qualified: 2,
817826
content: 1,
827+
description: 1,
818828
} as Record<string, number>,
819829
},
820830
};
@@ -836,30 +846,45 @@ export class LocalDocsSearch {
836846
static async create(opts?: { docsDir?: string }): Promise<LocalDocsSearch> {
837847
const instance = new LocalDocsSearch();
838848
instance.indexMethods(EMBEDDED_METHODS);
849+
for (const readme of EMBEDDED_READMES) {
850+
instance.indexProse(readme.content, `readme:${readme.language}`);
851+
}
839852
if (opts?.docsDir) {
840853
await instance.loadDocsDirectory(opts.docsDir);
841854
}
842855
return instance;
843856
}
844857

845-
// Note: Language is accepted for interface consistency with remote search, but currently has no
846-
// effect since this local search only supports TypeScript docs.
847858
search(props: {
848859
query: string;
849860
language?: string;
850861
detail?: string;
851862
maxResults?: number;
852863
maxLength?: number;
853864
}): SearchResult {
854-
const { query, detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
865+
const { query, language = 'typescript', detail = 'default', maxResults = 5, maxLength = 100_000 } = props;
855866

856867
const useMarkdown = detail === 'verbose' || detail === 'high';
857868

858-
// Search both indices and merge results by score
869+
// Search both indices and merge results by score.
870+
// Filter prose hits so language-tagged content (READMEs and docs with
871+
// frontmatter) only matches the requested language.
859872
const methodHits = this.methodIndex
860873
.search(query)
861874
.map((hit) => ({ ...hit, _kind: 'http_method' as const }));
862-
const proseHits = this.proseIndex.search(query).map((hit) => ({ ...hit, _kind: 'prose' as const }));
875+
const proseHits = this.proseIndex
876+
.search(query)
877+
.filter((hit) => {
878+
const source = ((hit as Record<string, unknown>)['_original'] as ProseChunk | undefined)?.source;
879+
if (!source) return true;
880+
// Check for language-tagged sources: "readme:<lang>" or "lang:<lang>:<filename>"
881+
let taggedLang: string | undefined;
882+
if (source.startsWith('readme:')) taggedLang = source.slice('readme:'.length);
883+
else if (source.startsWith('lang:')) taggedLang = source.split(':')[1];
884+
if (!taggedLang) return true;
885+
return taggedLang === language || (language === 'javascript' && taggedLang === 'typescript');
886+
})
887+
.map((hit) => ({ ...hit, _kind: 'prose' as const }));
863888
const merged = [...methodHits, ...proseHits].sort((a, b) => b.score - a.score);
864889
const top = merged.slice(0, maxResults);
865890

@@ -872,11 +897,16 @@ export class LocalDocsSearch {
872897
if (useMarkdown && m.markdown) {
873898
fullResults.push(m.markdown);
874899
} else {
900+
// Use per-language data when available, falling back to the
901+
// top-level fields (which are TypeScript-specific in the
902+
// legacy codepath).
903+
const langData = m.perLanguage?.[language];
875904
fullResults.push({
876-
method: m.qualified,
905+
method: langData?.method ?? m.qualified,
877906
summary: m.summary,
878907
description: m.description,
879908
endpoint: `${m.httpMethod.toUpperCase()} ${m.endpoint}`,
909+
...(langData?.example ? { example: langData.example } : {}),
880910
...(m.params ? { params: m.params } : {}),
881911
...(m.response ? { response: m.response } : {}),
882912
});
@@ -947,7 +977,19 @@ export class LocalDocsSearch {
947977
this.indexProse(texts.join('\n\n'), file.name);
948978
}
949979
} else {
950-
this.indexProse(content, file.name);
980+
// Parse optional YAML frontmatter for language tagging.
981+
// Files with a "language" field in frontmatter will only
982+
// surface in searches for that language.
983+
//
984+
// Example:
985+
// ---
986+
// language: python
987+
// ---
988+
// # Error handling in Python
989+
// ...
990+
const frontmatter = parseFrontmatter(content);
991+
const source = frontmatter.language ? `lang:${frontmatter.language}:${file.name}` : file.name;
992+
this.indexProse(content, source);
951993
}
952994
} catch (err) {
953995
getLogger().warn({ err, file: file.name }, 'Failed to index docs file');
@@ -1025,3 +1067,12 @@ function extractTexts(data: unknown, depth = 0): string[] {
10251067
}
10261068
return [];
10271069
}
1070+
1071+
/** Parses YAML frontmatter from a markdown string, extracting the language field if present. */
1072+
function parseFrontmatter(markdown: string): { language?: string } {
1073+
const match = markdown.match(/^---\n([\s\S]*?)\n---/);
1074+
if (!match) return {};
1075+
const body = match[1] ?? '';
1076+
const langMatch = body.match(/^language:\s*(.+)$/m);
1077+
return langMatch ? { language: langMatch[1]!.trim() } : {};
1078+
}

0 commit comments

Comments
 (0)