Skip to main content
Glama

Get Best Practices

gt_best_practices
Read-only

Fetch 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

TableJSON Schema
NameRequiredDescriptionDefault
libraryIdYesLibrary ID (from gt_resolve_library), npm:package, pypi:package, or library name like 'nextjs', 'react'
topicNoSpecific area: 'performance', 'security', 'testing', 'deployment', 'migration', 'patterns', 'v4 migration'. Leave empty for general best practices.
versionNoVersion to scope results to, e.g. '14', '3.0.3'. Focuses extraction on version-specific patterns.
tokensNoMax tokens to return

Implementation Reference

  • src/index.ts:70-70 (registration)
    Registration of the gt_best_practices tool via registerBestPracticesTool()
    registerBestPracticesTool(server);
  • 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"),
    });
  • 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",
    ];
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses that the tool accesses a proprietary registry under Elastic License 2.0 and imposes usage restrictions (no enumeration/dump), which goes beyond the readOnlyHint annotation by adding legal and behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three sentences: first states purpose, second sharpens scope, third provides essential legal notice. No redundancy, and each sentence adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema and full parameter coverage, the description adequately explains what the tool retrieves and the legal constraints. A brief note on return format would make it complete but is not critical.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema covers all parameters with descriptions (100% coverage). The description adds minor context for libraryId (e.g., from gt_resolve_library) but does not significantly enhance the schema information.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description precisely states the tool fetches best practices, patterns, and guidelines for libraries, and explicitly excludes generic reference docs, clearly distinguishing it from sibling tools like gt_get_docs.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Includes a proprietary data notice with explicit do's and don'ts for querying specific libraries only, and implies not to use for generic docs. However, it does not name an alternative tool for reference documentation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/rm-rf-prod/ws-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server