Skip to main content
Glama
ncukondo

PubMed MCP Server

by ncukondo

PubMed Full Text

get_fulltext

Retrieve full-text content of PubMed articles by providing PubMed IDs (PMIDs). This tool enables access to complete scientific article texts for research and analysis.

Instructions

Get full text content of PubMed articles using PMIDs.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pmidsYesArray of PubMed IDs (PMIDs) to get full text for

Implementation Reference

  • src/index.ts:210-241 (registration)
    MCP tool registration for 'get_fulltext', including schema and execution handler that delegates to getFullTextHandler
    server.registerTool(
      'get_fulltext',
      {
        title: 'PubMed Full Text',
        description: 'Get full text content of PubMed articles using PMIDs.',
        inputSchema: {
          pmids: z.array(z.string()).describe('Array of PubMed IDs (PMIDs) to get full text for')
        }
      },
      async ({ pmids }) => {
        try {
          const results = await getFullTextHandler.getFullText(pmids);
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(results, null, 2),
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `Error fetching full text: ${error instanceof Error ? error.message : 'Unknown error'}`,
              },
            ],
          };
        }
      }
    );
  • Factory function creating the getFullText handler that delegates execution to PubMedAPI
    export function createGetFullTextHandler(pubmedOptions: PubMedOptions): GetFullTextHandler {
      const pubmedApi = createPubMedAPI(pubmedOptions);
    
      return {
        async getFullText(pmids: string[]): Promise<FullTextResult[]> {
          return await pubmedApi.getFullText(pmids);
        }
      };
    }
  • Input schema for the 'get_fulltext' tool using Zod validation
      pmids: z.array(z.string()).describe('Array of PubMed IDs (PMIDs) to get full text for')
    }
  • Core implementation of getFullText in PubMedAPI: handles caching, full-text availability via PMC ID converter and elink, fetches XML from PMC efetch, extracts structured text content, decodes entities, and caches results
    const getFullText = async (pmids: string[]): Promise<FullTextResult[]> => {
      if (pmids.length === 0) return [];
    
      // Check cache for existing full texts if cache is enabled
      const cachedResults: FullTextResult[] = cache
        ? (await Promise.all(pmids.map(async (pmid) => {
          const cached = await cache.getCachedFullText(pmid);
          return cached ? { pmid, fullText: cached, cacheFilePath: cache.getFullTextFilePath(pmid) } : null;
        }))).filter((result) => result !== null)
        : [];
      const uncachedPmids: string[] = pmids.filter(
        pmid => !cachedResults.some(result => result.pmid === pmid)
      );
    
      // If all full texts are cached, return them
      if (uncachedPmids.length === 0) {
        return cachedResults;
      }
    
      // Batch check full text availability for uncached PMIDs
      const availabilityResultsArray = await checkFullTextAvailability(uncachedPmids);
    
      // Convert array to map for easier lookup
      const availabilityResults = Object.fromEntries(availabilityResultsArray);
    
      // Group PMIDs by their PMC IDs for batch fetching
      const pmcToPmidMap: { [pmcId: string]: string[] } = {};
      const resultsMap: { [pmid: string]: FullTextResult } = {};
    
      // Initialize results and group by PMC ID
      uncachedPmids.forEach(pmid => {
        const availability = availabilityResults[pmid];
        if (availability?.pmcId) {
          if (!pmcToPmidMap[availability.pmcId]) {
            pmcToPmidMap[availability.pmcId] = [];
          }
          pmcToPmidMap[availability.pmcId].push(pmid);
          // Store links for later assignment
          resultsMap[pmid] = { pmid, fullText: null, links: availability.links };
        } else {
          resultsMap[pmid] = { pmid, fullText: null, links: availability?.links || [] };
        }
      });
    
      // Batch fetch full texts for PMC IDs
      for (const [pmcId, relatedPmids] of Object.entries(pmcToPmidMap)) {
        try {
          // PMC efetch API expects PMC ID with 'PMC' prefix
          const pmcIdWithPrefix = pmcId.startsWith('PMC') ? pmcId : `PMC${pmcId}`;
          const params = {
            db: 'pmc',
            id: pmcIdWithPrefix,
            retmode: 'xml'
            // Note: PMC database only supports rettype: null (empty) per NCBI documentation
          };
    
          const url = buildUrl('efetch', params);
          const xmlResponse = await makeRequest(url);
          const parsedData = parser.parse(xmlResponse);
    
          const article = parsedData['pmc-articleset']?.article || parsedData.pmc_articleset?.article || parsedData.article;
    
          if (article) {
            const extractTextFromNode = (node: unknown): string => {
              if (node == null) return ''
    
              if (typeof node === 'string') {
                return decodeHtmlEntities(node)
              }
    
              if (Array.isArray(node)) {
                return node
                  .map(extractTextFromNode)
                  .filter(text => text.length > 0)
                  .join('\n\n') // Use paragraph breaks for array elements
              }
    
              if (typeof node === 'object') {
                const obj = node as Record<string, unknown>
                const textValue = obj['#text']
                if (typeof textValue === 'string') {
                  return decodeHtmlEntities(textValue)
                }
    
                let text = ''
                for (const value of Object.values(obj)) {
                  text += extractTextFromNode(value) + ' '
                }
                return text.trim()
              }
    
              return ''
            }
    
            let fullText = '';
    
            if (article.front?.['article-meta']?.['title-group']?.['article-title']) {
              const title = extractTextFromNode(article.front['article-meta']['title-group']['article-title']);
              fullText += `# ${title}\n\n`;
            }
    
            if (article.front?.['article-meta']?.abstract) {
              const abstract = extractTextFromNode(article.front['article-meta'].abstract);
              fullText += `## Abstract\n\n${abstract}\n\n`;
            }
    
            if (article.body) {
              // Try to extract structured content first
              const structuredContent = extractStructuredContent(article.body, extractTextFromNode);
              if (structuredContent) {
                fullText += `## Content\n\n${structuredContent}`;
              } else {
                // Fallback to basic text extraction
                const content = extractTextFromNode(article.body);
                fullText += `## Content\n\n${content}\n\n`;
              }
            }
    
            // Clean up text formatting
            fullText = fullText
              .replace(/[ \t]+/g, ' ')                    // Multiple spaces/tabs to single space
              .trim();
    
            // Assign the same full text to all related PMIDs and cache it
            for (const pmid of relatedPmids) {
              const existingLinks = resultsMap[pmid]?.links;
              resultsMap[pmid] = {
                pmid,
                fullText: fullText || null,
                ...(existingLinks && existingLinks.length > 0 && { links: existingLinks })
              };
    
              // Cache the full text if cache is enabled and fullText is not null
              if (cache && fullText) {
                try {
                  await cache.setCachedFullText(pmid, fullText);
                  resultsMap[pmid].cacheFilePath = cache.getFullTextFilePath(pmid);
                } catch (err) {
                  console.error('Error caching full text:', err);
                }
              }
            }
          } else {
            // No article found for this PMC ID
            relatedPmids.forEach(pmid => {
              const existingLinks = resultsMap[pmid]?.links;
              resultsMap[pmid] = {
                pmid,
                fullText: null,
                ...(existingLinks && existingLinks.length > 0 && { links: existingLinks })
              };
            });
          }
        } catch (error) {
          console.error(`Error fetching full text for PMC ID ${pmcId}:`, error);
          relatedPmids.forEach(pmid => {
            const existingLinks = resultsMap[pmid]?.links;
            resultsMap[pmid] = {
              pmid,
              fullText: null,
              ...(existingLinks && existingLinks.length > 0 && { links: existingLinks })
            };
          });
        }
      }
    
      // Combine cached and fetched results, maintaining the original order
      const allResults = [...cachedResults, ...Object.values(resultsMap)];
      return pmids.map(pmid => allResults.find(result => result.pmid === pmid)).filter(Boolean) as FullTextResult[];
    };
Behavior2/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 states the tool retrieves full text but doesn't disclose behavioral traits such as rate limits, authentication needs, error handling (e.g., for invalid PMIDs), or output format (e.g., plain text, HTML). For a tool with no annotation coverage, this is a significant gap.

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 a single, efficient sentence with zero waste. It front-loads the purpose clearly and uses straightforward language, making it easy to parse. Every word earns its place.

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 the lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., full text content in what format?), potential limitations (e.g., availability of full text), or error cases. For a tool with no structured support, more context is needed to be fully helpful.

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 schema description coverage is 100%, with the parameter 'pmids' clearly documented in the schema as an array of PubMed IDs. The description adds minimal value beyond the schema by mentioning 'using PMIDs', but doesn't provide additional semantics like format examples or constraints. Baseline 3 is appropriate when 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 action ('Get full text content') and resource ('PubMed articles') with a specific mechanism ('using PMIDs'). It distinguishes from sibling tools like 'fetch_summary' (which presumably provides summaries) and 'search_pubmed' (which searches rather than retrieves full text). However, it doesn't explicitly mention how it differs from siblings beyond the verb, keeping it at 4 rather than 5.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like 'fetch_summary' or 'search_pubmed'. It doesn't specify prerequisites (e.g., needing valid PMIDs) or exclusions (e.g., not for abstracts). Without any usage context, it scores low.

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/ncukondo/pubmed-mcp'

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