Skip to main content
Glama

get-library-docs

Fetch current library documentation from Context7 MCP to access up-to-date information and code examples, ensuring accurate API references and eliminating outdated training data.

Instructions

Fetches up-to-date documentation for a library. You must call 'resolve-library-id' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
context7CompatibleLibraryIDYesExact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolve-library-id' or directly from user query in the format '/org/project' or '/org/project/version'.
topicNoTopic to focus documentation on (e.g., 'hooks', 'routing').
tokensNoMaximum number of tokens of documentation to retrieve (default: 10000). Higher values provide more context but consume more tokens.

Implementation Reference

  • MCP tool handler function that invokes the fetchLibraryDocumentation helper, handles errors, and returns formatted MCP response content.
    async ({ context7CompatibleLibraryID, tokens = DEFAULT_MINIMUM_TOKENS, topic = "" }) => {
      const fetchDocsResponse = await fetchLibraryDocumentation(context7CompatibleLibraryID, {
        tokens,
        topic,
      });
    
      if (!fetchDocsResponse) {
        return {
          content: [
            {
              type: "text",
              text: "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolve-library-id' with the package name you wish to retrieve documentation for.",
            },
          ],
        };
      }
    
      return {
        content: [
          {
            type: "text",
            text: fetchDocsResponse,
          },
        ],
      };
    }
  • Zod schema for tool input parameters including required library ID, optional topic filter, and token limit with preprocessing and transformation.
    {
      context7CompatibleLibraryID: z
        .string()
        .describe(
          "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolve-library-id' or directly from user query in the format '/org/project' or '/org/project/version'."
        ),
      topic: z
        .string()
        .optional()
        .describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
      tokens: z
        .preprocess((val) => (typeof val === "string" ? Number(val) : val), z.number())
        .transform((val) => (val < DEFAULT_MINIMUM_TOKENS ? DEFAULT_MINIMUM_TOKENS : val))
        .optional()
        .describe(
          `Maximum number of tokens of documentation to retrieve (default: ${DEFAULT_MINIMUM_TOKENS}). Higher values provide more context but consume more tokens.`
        ),
    },
  • src/index.ts:132-179 (registration)
    Registration of the 'get-library-docs' tool on the MCP server instance, specifying name, description, input schema, and handler.
    server.tool(
      "get-library-docs",
      "Fetches up-to-date documentation for a library. You must call 'resolve-library-id' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.",
      {
        context7CompatibleLibraryID: z
          .string()
          .describe(
            "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolve-library-id' or directly from user query in the format '/org/project' or '/org/project/version'."
          ),
        topic: z
          .string()
          .optional()
          .describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
        tokens: z
          .preprocess((val) => (typeof val === "string" ? Number(val) : val), z.number())
          .transform((val) => (val < DEFAULT_MINIMUM_TOKENS ? DEFAULT_MINIMUM_TOKENS : val))
          .optional()
          .describe(
            `Maximum number of tokens of documentation to retrieve (default: ${DEFAULT_MINIMUM_TOKENS}). Higher values provide more context but consume more tokens.`
          ),
      },
      async ({ context7CompatibleLibraryID, tokens = DEFAULT_MINIMUM_TOKENS, topic = "" }) => {
        const fetchDocsResponse = await fetchLibraryDocumentation(context7CompatibleLibraryID, {
          tokens,
          topic,
        });
    
        if (!fetchDocsResponse) {
          return {
            content: [
              {
                type: "text",
                text: "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolve-library-id' with the package name you wish to retrieve documentation for.",
              },
            ],
          };
        }
    
        return {
          content: [
            {
              type: "text",
              text: fetchDocsResponse,
            },
          ],
        };
      }
    );
  • Supporting utility function that performs the actual API request to Context7 to fetch library documentation based on library ID, with token and topic parameters, including error handling and normalization.
    export async function fetchLibraryDocumentation(
      libraryId: string,
      options: {
        tokens?: number;
        topic?: string;
      } = {}
    ): Promise<string | null> {
      try {
        if (libraryId.startsWith("/")) {
          libraryId = libraryId.slice(1);
        }
        const url = new URL(`${CONTEXT7_API_BASE_URL}/v1/${libraryId}`);
        if (options.tokens) url.searchParams.set("tokens", options.tokens.toString());
        if (options.topic) url.searchParams.set("topic", options.topic);
        url.searchParams.set("type", DEFAULT_TYPE);
        const response = await fetch(url, {
          headers: {
            "X-Context7-Source": "mcp-server",
          },
        });
        if (!response.ok) {
          const errorCode = response.status;
          if (errorCode === 429) {
            const errorMessage = `Rate limited due to too many requests. Please try again later.`;
            console.error(errorMessage);
            return errorMessage;
          }
          const errorMessage = `Failed to fetch documentation. Please try again later. Error code: ${errorCode}`;
          console.error(errorMessage);
          return errorMessage;
        }
        const text = await response.text();
        if (!text || text === "No content available" || text === "No context data available") {
          return null;
        }
        return text;
      } catch (error) {
        const errorMessage = `Error fetching library documentation. Please try again later. ${error}`;
        console.error(errorMessage);
        return errorMessage;
      }
    }
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It mentions the need for a 'Context7-compatible library ID' and implies it fetches documentation, but lacks details on behavioral traits like rate limits, error handling, or what 'up-to-date' means. It adds some context (e.g., ID format requirements) but is incomplete for a tool with no annotation coverage.

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?

The description is concise and front-loaded: it starts with the core purpose, then immediately provides critical usage guidelines. Both sentences are essential—the first defines the tool, and the second explains prerequisites—with no wasted words, making it highly efficient.

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

Completeness3/5

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

Given no annotations and no output schema, the description is moderately complete. It covers the purpose and usage well but lacks details on behavior (e.g., response format, errors) and output. For a tool with 3 parameters and no structured safety hints, it should do more to compensate, leaving gaps in contextual understanding.

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 description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal value beyond the schema by mentioning the ID format and prerequisite, but doesn't provide additional semantics for parameters like 'topic' or 'tokens'. Baseline 3 is appropriate as the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Fetches up-to-date documentation for a library.' It specifies the resource (library documentation) and the action (fetching). However, it doesn't explicitly differentiate from the sibling 'resolve-library-id' beyond mentioning it as a prerequisite, so it falls short of a perfect 5.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool vs. alternatives: it states that 'resolve-library-id' must be called first unless the user provides a library ID directly. This clearly defines the prerequisite and alternative scenarios, making it easy for an agent to decide when to invoke this tool.

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/2511319/context7'

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