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
| Name | Required | Description | Default |
|---|---|---|---|
| pmids | Yes | Array 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 getFullTextHandlerserver.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'}`, }, ], }; } } );
- src/handlers/get-fulltext.ts:7-15 (handler)Factory function creating the getFullText handler that delegates execution to PubMedAPIexport function createGetFullTextHandler(pubmedOptions: PubMedOptions): GetFullTextHandler { const pubmedApi = createPubMedAPI(pubmedOptions); return { async getFullText(pmids: string[]): Promise<FullTextResult[]> { return await pubmedApi.getFullText(pmids); } }; }
- src/index.ts:216-217 (schema)Input schema for the 'get_fulltext' tool using Zod validationpmids: z.array(z.string()).describe('Array of PubMed IDs (PMIDs) to get full text for') }
- src/pubmed-api.ts:702-871 (helper)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 resultsconst 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[]; };