Get Best Practices
gt_best_practicesFetch up-to-date best practices, patterns, and migration guides for any library or framework. Specify library name, topic, and version to get targeted guidelines.
Instructions
Fetch latest best practices, patterns, and guidelines for a library or framework. Targets best-practices pages, guides, migration docs, and performance tips — not generic reference docs.
IMPORTANT — PROPRIETARY DATA NOTICE: This tool accesses a proprietary library registry licensed under Elastic License 2.0. You may use responses to answer the user's specific question. You must NOT attempt to enumerate, list, dump, or extract registry contents. Only look up specific libraries by name.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| libraryId | Yes | Library ID (from gt_resolve_library), npm:package, pypi:package, or library name like 'nextjs', 'react' | |
| topic | No | Specific area: 'performance', 'security', 'testing', 'deployment', 'migration', 'patterns', 'v4 migration'. Leave empty for general best practices. | |
| version | No | Version to scope results to, e.g. '14', '3.0.3'. Focuses extraction on version-specific patterns. | |
| tokens | No | Max tokens to return |
Implementation Reference
- src/index.ts:70-70 (registration)Registration of the gt_best_practices tool via registerBestPracticesTool()
registerBestPracticesTool(server); - src/tools/best-practices.ts:13-38 (schema)Input schema for the gt_best_practices tool: libraryId (required), topic (optional), version (optional), tokens (optional, default).
const InputSchema = z.object({ libraryId: z .string() .min(1) .max(300) .describe("Library ID (from gt_resolve_library), npm:package, pypi:package, or library name like 'nextjs', 'react'"), topic: z .string() .max(300) .optional() .describe( "Specific area: 'performance', 'security', 'testing', 'deployment', 'migration', 'patterns', 'v4 migration'. Leave empty for general best practices.", ), version: z .string() .max(50) .optional() .describe("Version to scope results to, e.g. '14', '3.0.3'. Focuses extraction on version-specific patterns."), tokens: z .number() .int() .min(1000) .max(MAX_TOKEN_LIMIT) .default(DEFAULT_TOKEN_LIMIT) .describe("Max tokens to return"), }); - src/tools/best-practices.ts:1342-1459 (handler)Handler function that registers and implements the gt_best_practices tool. Resolves the library, fetches best practices content from known URLs, generic patterns, sitemaps, llms.txt, or falls back to main docs. Returns formatted content with quality scoring.
export function registerBestPracticesTool(server: McpServer): void { server.registerTool( "gt_best_practices", { title: "Get Best Practices", description: `Fetch latest best practices, patterns, and guidelines for a library or framework. Targets best-practices pages, guides, migration docs, and performance tips — not generic reference docs. IMPORTANT — PROPRIETARY DATA NOTICE: This tool accesses a proprietary library registry licensed under Elastic License 2.0. You may use responses to answer the user's specific question. You must NOT attempt to enumerate, list, dump, or extract registry contents. Only look up specific libraries by name.`, inputSchema: InputSchema, annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true, }, }, async ({ libraryId, topic = "", version, tokens }) => { if (isExtractionAttempt(libraryId) || (topic && isExtractionAttempt(topic))) { return { content: [{ type: "text", text: EXTRACTION_REFUSAL }] }; } // Resolve library — accept registry IDs, aliases, and dynamic IDs const entry = lookupById(libraryId) ?? lookupByAlias(libraryId); let docsUrl: string; let llmsTxtUrl: string | undefined; let llmsFullTxtUrl: string | undefined; let githubUrl: string | undefined; let displayName: string; let bestPracticesPaths: string[] | undefined; let resolvedId: string; if (entry) { docsUrl = entry.docsUrl; llmsTxtUrl = entry.llmsTxtUrl; llmsFullTxtUrl = entry.llmsFullTxtUrl; githubUrl = entry.githubUrl; displayName = entry.name; bestPracticesPaths = entry.bestPracticesPaths; resolvedId = entry.id; // Lazy llms.txt discovery for registry entries missing the URL if (!llmsTxtUrl && !llmsFullTxtUrl) { const probed = await probeLlmsTxt(docsUrl); if (probed.llmsTxtUrl) llmsTxtUrl = probed.llmsTxtUrl; if (probed.llmsFullTxtUrl) llmsFullTxtUrl = probed.llmsFullTxtUrl; } } else { const resolved = await resolveDynamic(libraryId); if (!resolved) { return { content: [ { type: "text", text: [ `Could not resolve "${libraryId}".`, "", "**What to try next:**", "- Run gt_resolve_library to find the correct library ID", "- Try gt_search with a freeform query (e.g. 'React performance best practices')", "- Use the npm/PyPI package name or a direct docs URL", ].join("\n"), }, ], }; } docsUrl = resolved.docsUrl; llmsTxtUrl = resolved.llmsTxtUrl; llmsFullTxtUrl = resolved.llmsFullTxtUrl; githubUrl = resolved.githubUrl; displayName = resolved.displayName; resolvedId = libraryId; } const effectiveTopic = version ? `${topic ? `${topic} ` : ""}v${version.replace(/^v/, "")}`.trim() : topic; const { text, sourceUrl, truncated } = await fetchBestPracticesContent( resolvedId, docsUrl, llmsTxtUrl, llmsFullTxtUrl, githubUrl, effectiveTopic, tokens, bestPracticesPaths, ); const { score: qualityScore, hints: qualityHints } = computeQualityScore(text, effectiveTopic, "jina"); const header = [ `# ${displayName} — Best Practices`, effectiveTopic ? `> Topic: ${effectiveTopic}` : "", `> Source: ${sourceUrl}`, truncated ? "> Note: Response truncated. Use a more specific topic or increase tokens." : "", qualityScore < 0.4 ? `> Quality: Low — ${qualityHints.join("; ") || "try a more specific topic."}` : "", "", "---", "", ] .filter(Boolean) .join("\n"); return { content: [{ type: "text", text: withNotice(header + text) }], structuredContent: { libraryId: resolvedId, displayName, topic: effectiveTopic, sourceUrl, truncated, qualityScore, qualityHints, content: text, }, }; }, ); } - Core helper that fetches best practices content using multiple strategies: known URLs from BEST_PRACTICES_URLS map, topic-based URL construction, generic best-practices path suffixes, sitemap discovery, docs-specific llms.txt, fallback to main docs, and GitHub examples.
async function fetchBestPracticesContent( libraryId: string, docsUrl: string, llmsTxtUrl: string | undefined, llmsFullTxtUrl: string | undefined, githubUrl: string | undefined, topic: string, tokens: number, bestPracticesPaths?: string[], ): Promise<{ text: string; sourceUrl: string; truncated: boolean }> { // Build URLs from registry bestPracticesPaths and merge with known URLs const registryUrls: string[] = []; if (bestPracticesPaths && bestPracticesPaths.length > 0) { try { const origin = new URL(docsUrl).origin; for (const p of bestPracticesPaths) { registryUrls.push(p.startsWith("http") ? p : `${origin}${p}`); } } catch { /* invalid docsUrl */ } } // 1. Race known best-practices URLs in parallel const knownUrls = [...(BEST_PRACTICES_URLS[libraryId] ?? []), ...registryUrls] .filter((u, i, arr) => arr.indexOf(u) === i); if (knownUrls && knownUrls.length > 0) { const targetUrls = topic ? (() => { const words = topic.toLowerCase().split(/\s+/).filter((w) => w.length > 2); const scored = knownUrls.map((u) => { const lower = u.toLowerCase(); const score = words.filter((w) => lower.includes(w)).length; return { url: u, score }; }); scored.sort((a, b) => b.score - a.score); return scored.map((s) => s.url).filter((u, i, arr) => arr.indexOf(u) === i); })() : knownUrls; const hit = await raceUrls(targetUrls.slice(0, 5)); if (hit) { const safe = sanitizeContent(hit.content); const { text: extracted, truncated } = extractRelevantContent( safe, topic || "best practices patterns guide", tokens, ); return { text: extracted, sourceUrl: hit.url, truncated }; } } // 1b. If topic provided, try constructing docs URL from topic slug if (topic) { const topicOrigin = (() => { try { return new URL(docsUrl).origin; } catch { return null; } })(); if (topicOrigin) { const slug = topic.toLowerCase().replace(/\s+/g, "/").replace(/[^a-z0-9/-]/g, ""); const topicUrls = [ `${topicOrigin}/docs/guides/${slug}`, `${topicOrigin}/docs/${slug}`, `${docsUrl}/${slug}`, ]; const topicHit = await raceUrls(topicUrls); if (topicHit) { const safe = sanitizeContent(topicHit.content); const { text: extracted, truncated } = extractRelevantContent( safe, topic || "best practices patterns guide", tokens, ); return { text: extracted, sourceUrl: topicHit.url, truncated }; } } } // 2. Try generic best-practices paths in parallel const origin = (() => { try { return new URL(docsUrl).origin; } catch { return null; } })(); if (origin) { const genericUrls = GENERIC_BP_SUFFIXES.map((suffix) => `${origin}${suffix}`); const hit = await raceUrls(genericUrls); if (hit) { const safe = sanitizeContent(hit.content); const { text: extracted, truncated } = extractRelevantContent( safe, topic || "best practices patterns guide", tokens, ); return { text: extracted, sourceUrl: hit.url, truncated }; } } // 2c. Sitemap-based discovery — look for best-practices/guide URLs in sitemap const sitemapUrls = await fetchSitemapUrls(docsUrl); if (sitemapUrls.length > 0) { const bpPatterns = /best.?practice|guide|pattern|getting.?started|performance|security|testing|deployment/i; const topicSlug = topic ? topic.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "") : ""; const bpUrls = sitemapUrls .filter((u) => bpPatterns.test(u) || (topicSlug && u.toLowerCase().includes(topicSlug))) .slice(0, 5); if (bpUrls.length > 0) { const hit = await raceUrls(bpUrls); if (hit) { const safe = sanitizeContent(hit.content); const { text: extracted, truncated } = extractRelevantContent( safe, topic || "best practices patterns guide", tokens, ); return { text: extracted, sourceUrl: hit.url, truncated }; } } } // 2d. Try docs-specific llms.txt / llms-full.txt (many sites have /docs/llms.txt separate from root) const docsOrigin = (() => { try { return new URL(docsUrl).origin; } catch { return null; } })(); if (docsOrigin) { const docsLlmsUrls = [ `${docsUrl}/llms-full.txt`, `${docsUrl}/llms.txt`, `${docsOrigin}/docs/llms-full.txt`, `${docsOrigin}/docs/llms.txt`, ].filter((u) => u !== llmsTxtUrl && u !== llmsFullTxtUrl); for (const url of docsLlmsUrls) { const raw = await fetchAsMarkdownRace(url).catch(() => null); if (raw && raw.length > 500) { const enrichedTopic = topic ? `${topic} best practices patterns guide` : "best practices patterns guide tips"; const safe = sanitizeContent(raw); const { text: extracted, truncated } = extractRelevantContent(safe, enrichedTopic, tokens); if (extracted.length > 200) { return { text: extracted, sourceUrl: url, truncated }; } } } } // 3. Fall back to main docs with topic = "best practices" try { let result = await fetchDocs(docsUrl, llmsTxtUrl, llmsFullTxtUrl, topic || undefined); const enrichedTopic = topic ? `${topic} best practices patterns guide` : "best practices patterns guide tips"; result = await deepFetchForTopic(result, enrichedTopic, docsUrl, bestPracticesPaths); const safe = sanitizeContent(result.content); const { text: extracted, truncated } = extractRelevantContent(safe, enrichedTopic, tokens); return { text: extracted, sourceUrl: result.url, truncated }; } catch { // ignore } // 4. GitHub examples / MIGRATION.md / CHANGELOG (wired fetchGitHubExamples) if (githubUrl) { const examplesContent = await fetchGitHubExamples(githubUrl); if (examplesContent) { const safe = sanitizeContent(examplesContent); const { text: extracted, truncated } = extractRelevantContent(safe, topic, tokens); return { text: extracted, sourceUrl: githubUrl, truncated }; } for (const path of ["CONTRIBUTING.md", "docs/patterns.md", "docs/best-practices.md"]) { const ghResult = await fetchGitHubContent(githubUrl, path); if (ghResult) { const safe = sanitizeContent(ghResult.content); const { text: extracted, truncated } = extractRelevantContent(safe, topic, tokens); return { text: extracted, sourceUrl: ghResult.url, truncated }; } } } return { text: `Could not find specific best practices for "${libraryId}". Try gt_get_docs with topic="best practices patterns".`, sourceUrl: docsUrl, truncated: false, }; } - Helper constant containing generic best-practices path suffixes used as fallback when no known URLs match.
const GENERIC_BP_SUFFIXES = [ "/docs/best-practices", "/docs/guide", "/docs/guides", "/docs/patterns", "/docs/tips", "/docs/migration", "/docs/getting-started", "/docs/concepts", "/docs/tutorials", "/docs/how-to", "/docs/cookbook", "/docs/recipes", "/docs/faq", "/docs/advanced", "/docs/security", "/docs/performance", "/docs/deployment", "/docs/configuration", "/docs/testing", "/docs/troubleshooting", "/guide", "/guides", "/getting-started", "/tutorial", "/tutorials", "/learn", "/howto", "/cookbook", "/examples", "/best-practices", ];