Skip to main content
Glama

Get docs for an npm package

get_docs_for_npm_package

Retrieve documentation for npm packages to access README files and API information directly within your IDE.

Instructions

Get the docs for an npm package

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
packageNameYesName of the npm package

Implementation Reference

  • The core handler function for the 'get_docs_for_npm_package' tool. It fetches the latest package metadata from the npm registry, attempts to retrieve the README.md from the GitHub repository (trying common branches: master, main, develop), and falls back to downloading and extracting the package tarball to locate README files if GitHub fails.
    async ({ packageName }) => {
      try {
        console.error(`Processing request for package: ${packageName}`);
    
        const npmPackage = await fetch(`https://registry.npmjs.org/${packageName}/latest`).then( res => res.json() as Promise<NpmRegistryResponse>);
        const tarball = npmPackage.dist.tarball;
        const repoUrl = npmPackage.repository?.url; 
        let docTxt = '';
    
        // First, try to get docs from GitHub repository if available
        if (repoUrl) {
          const repoPath = extractGitHubRepoPath(repoUrl);
          if (repoPath) {
            console.error("repoPath", repoPath);
            
            // Try multiple branch names to find the README
            const branches = ['master', 'main', 'develop'];
            
            for (const branch of branches) {
              try {
                const response = await fetch(`https://raw.githubusercontent.com/${repoPath}/refs/heads/${branch}/README.md`);
                if (response.ok) {
                  docTxt = await response.text();
                  break;
                }
              } catch (error) {
                console.error(`Failed to fetch README from ${branch} branch:`, error);
                continue;
              }
            }
          }
        }
        
        // If no docs found from GitHub, try tarball fallback
        if (!docTxt) {
          try {
            docTxt = await extractTarballAndGetReadme(tarball, packageName);
          } catch (error) {
            console.error('Failed to extract tarball:', error);
          }
        }
        
        // Return the result
        if (docTxt) {
          return {
            content: [{
              type: "text",
              text: docTxt
            }]
          };
        } else {
          return {
            content: [{
              type: "text",
              text: "No documentation found in any common branches or package tarball"
            }]
          };
        }
        
      } catch (error) {
        console.error('Error in tool execution:', error);
        return {
          content: [{
            type: 'text',
            text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`
          }],
          isError: true
        };
      }
    }
  • Tool schema definition including title, description, and Zod-validated input schema requiring a 'packageName' string.
    {
      title: 'Get docs for an npm package',
      description: 'Get the docs for an npm package',
      inputSchema: {
        packageName: z.string().describe("Name of the npm package")
      }
    },
  • src/server.ts:107-186 (registration)
    Registration of the 'get_docs_for_npm_package' tool with the MCP server, including name, schema, and inline handler.
    server.registerTool(
      'get_docs_for_npm_package',
      {
        title: 'Get docs for an npm package',
        description: 'Get the docs for an npm package',
        inputSchema: {
          packageName: z.string().describe("Name of the npm package")
        }
      },
      async ({ packageName }) => {
        try {
          console.error(`Processing request for package: ${packageName}`);
    
          const npmPackage = await fetch(`https://registry.npmjs.org/${packageName}/latest`).then( res => res.json() as Promise<NpmRegistryResponse>);
          const tarball = npmPackage.dist.tarball;
          const repoUrl = npmPackage.repository?.url; 
          let docTxt = '';
    
          // First, try to get docs from GitHub repository if available
          if (repoUrl) {
            const repoPath = extractGitHubRepoPath(repoUrl);
            if (repoPath) {
              console.error("repoPath", repoPath);
              
              // Try multiple branch names to find the README
              const branches = ['master', 'main', 'develop'];
              
              for (const branch of branches) {
                try {
                  const response = await fetch(`https://raw.githubusercontent.com/${repoPath}/refs/heads/${branch}/README.md`);
                  if (response.ok) {
                    docTxt = await response.text();
                    break;
                  }
                } catch (error) {
                  console.error(`Failed to fetch README from ${branch} branch:`, error);
                  continue;
                }
              }
            }
          }
          
          // If no docs found from GitHub, try tarball fallback
          if (!docTxt) {
            try {
              docTxt = await extractTarballAndGetReadme(tarball, packageName);
            } catch (error) {
              console.error('Failed to extract tarball:', error);
            }
          }
          
          // Return the result
          if (docTxt) {
            return {
              content: [{
                type: "text",
                text: docTxt
              }]
            };
          } else {
            return {
              content: [{
                type: "text",
                text: "No documentation found in any common branches or package tarball"
              }]
            };
          }
          
        } catch (error) {
          console.error('Error in tool execution:', error);
          return {
            content: [{
              type: 'text',
              text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`
            }],
            isError: true
          };
        }
      }
    );
  • Helper function to download the npm package tarball, extract it to a temp directory, locate the package folder, find and read README files (various names/cases), and clean up.
    export async function extractTarballAndGetReadme(tarballUrl: string, packageName: string): Promise<string> {
      try {
        // Create a temporary directory for extraction
        const tempDir = path.join(os.tmpdir(), `npm-docs-${packageName}-${Date.now()}`);
        await fs.ensureDir(tempDir);
        
        // Download the tarball
        const response = await fetch(tarballUrl);
        if (!response.ok) {
          throw new Error(`Failed to download tarball: ${response.statusText}`);
        }
        
        const tarballBuffer = await response.arrayBuffer();
        
        // Extract filename from tarball URL
        const urlParts = tarballUrl.split('/');
        const tarballFilename = urlParts[urlParts.length - 1];
        if (!tarballFilename) {
          throw new Error('Could not extract filename from tarball URL');
        }
        const tarballPath = path.join(tempDir, tarballFilename);
    
        // Write tarball to file
        await fs.writeFile(tarballPath, Buffer.from(tarballBuffer));
        
        // Extract the tarball
        await tar.extract({
          file: tarballPath,
          cwd: tempDir
        });
        
        // Find the package directory (usually named package-version)
        const extractedDirs = await fs.readdir(tempDir);
        const packageDir = extractedDirs.find(dir => dir.startsWith('package'));
        
        if (!packageDir) {
          throw new Error('Could not find package directory in tarball');
        }
        
        const packagePath = path.join(tempDir, packageDir);
        
        // Look for README files (case insensitive)
        const readmeFiles = ['README.md', 'readme.md', 'README.txt', 'readme.txt', 'README'];
        let readmeContent = '';
        
        for (const readmeFile of readmeFiles) {
          const readmePath = path.join(packagePath, readmeFile);
          if (await fs.pathExists(readmePath)) {
            readmeContent = await fs.readFile(readmePath, 'utf-8');
            break;
          }
        }
        
        // Clean up temporary files
        await fs.remove(tempDir);
        
        return readmeContent || 'No README file found in package';
        
      } catch (error) {
        console.error('Error extracting tarball:', error);
        throw error;
      }
    }
  • Helper function to parse GitHub repository URL (handling git+ prefix and .git suffix) and extract the owner/repo path for raw.githubusercontent.com access.
    function extractGitHubRepoPath(githubUrl: string): string | null {
      try {
        // Handle git+https:// URLs
        const cleanUrl = githubUrl.replace(/^git\+/, '');
        
        // Parse the URL
        const url = new URL(cleanUrl);
        
        // Check if it's a GitHub URL
        if (url.hostname === 'github.com') {
          // Extract the pathname and remove leading slash
          const path = url.pathname.substring(1);
          
          // Remove .git extension if present
          return path.replace(/\.git$/, '');
        }
        
        return null;
      } catch (error) {
        console.error('Error parsing GitHub URL:', error);
        return null;
      }
    }
  • TypeScript interface defining the structure of the npm registry response used in the handler for accessing repository URL and tarball.
    export interface NpmRegistryResponse{
        name: string
        repository?:{
            type?: "git"
            url: string
        }
        dist:{
            tarball: string
        }
    }
Behavior1/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 of behavioral disclosure. It only states the action without detailing how it works—such as source of docs (e.g., npm registry, GitHub), format of return (e.g., markdown, JSON), error handling, or any constraints like rate limits or authentication needs. This is inadequate 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.

Conciseness4/5

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

The description is a single, straightforward sentence that efficiently conveys the core action. It is front-loaded with no unnecessary words, making it easy to parse. However, it is overly terse, missing details that could enhance usability without sacrificing brevity.

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

Completeness2/5

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

Given no annotations, no output schema, and a simple input schema, the description is incomplete. It fails to explain what 'docs' include, the return format, or any behavioral aspects like error cases. For a tool with minimal structured data, the description should provide more context to guide the agent effectively.

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?

The input schema has 100% description coverage, with the parameter 'packageName' clearly documented. The description does not add any meaning beyond the schema, as it only repeats the tool's purpose without elaborating on parameter usage (e.g., package naming conventions or validation). With high schema coverage, the baseline score of 3 is appropriate, as the schema handles parameter documentation adequately.

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

Purpose2/5

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

The description 'Get the docs for an npm package' restates the title and name with minimal elaboration. It specifies the verb 'Get' and resource 'docs for an npm package', but lacks detail on what 'docs' entails (e.g., README, API documentation, or installation guides) or how they are retrieved. Without sibling tools, differentiation isn't needed, but the purpose remains vague beyond basic restatement.

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

Usage Guidelines1/5

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

No guidance is provided on when to use this tool. The description does not mention prerequisites, alternatives, or context for usage (e.g., vs. searching npm registry or checking package versions). With no sibling tools, explicit alternatives aren't required, but general usage context is missing, leaving the agent without direction.

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/meanands/npm-package-docs-mcp'

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