Skip to main content
Glama
ncukondo

PubMed MCP Server

by ncukondo

PubMed Search

search_pubmed

Search PubMed for scientific articles using queries, date filters, and sorting options to find relevant research publications.

Instructions

Search PubMed for scientific articles.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query for PubMed
searchOptionsNoOptional search parameters

Implementation Reference

  • Inline asynchronous handler function for the 'search_pubmed' tool. Processes input parameters, handles date range logic, invokes searchHandler.search, and formats the response as MCP content.
    async ({ query, searchOptions }) => {
      try {
        const options = { ...(searchOptions || {}) };
    
        // If dateFrom is provided but dateTo is missing, set dateTo to today's date
        if (options.dateFrom && !options.dateTo) {
          const now = new Date();
          const yyyy = now.getFullYear();
          const mm = String(now.getMonth() + 1).padStart(2, '0');
          const dd = String(now.getDate()).padStart(2, '0');
          options.dateTo = `${yyyy}/${mm}/${dd}`;
        }
    
        const results = await searchHandler.search(query, options);
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(results, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Error searching PubMed: ${error instanceof Error ? error.message : 'Unknown error'}`,
            },
          ],
        };
      }
    }
  • Zod input schema definition for the 'search_pubmed' tool, defining 'query' as required string and optional 'searchOptions' object with retMax, retStart, sort, dateFrom, dateTo.
    inputSchema: {
      query: z.string().describe('Search query for PubMed'),
      searchOptions: z
        .object({
          retMax: z.number().optional().describe('Maximum number of results to return'),
          retStart: z.number().optional().describe('Starting index for results'),
          sort: z
            .enum(['relevance', 'pub_date', 'author', 'journal'])
            .optional()
            .describe('Sort order for results'),
          dateFrom: z.string().optional().describe('Start date filter (YYYY/MM/DD format)'),
          dateTo: z.string().optional().describe('End date filter (YYYY/MM/DD format)(If dateFrom is provided but dateTo is missing, set dateTo to today\'s date)'),
        })
        .optional()
        .describe('Optional search parameters'),
    },
  • src/index.ts:120-175 (registration)
    Complete registration of the 'search_pubmed' MCP tool using server.registerTool, including metadata, Zod input schema, and the primary handler function.
    server.registerTool(
      'search_pubmed',
      {
        title: 'PubMed Search',
        description: 'Search PubMed for scientific articles.',
        inputSchema: {
          query: z.string().describe('Search query for PubMed'),
          searchOptions: z
            .object({
              retMax: z.number().optional().describe('Maximum number of results to return'),
              retStart: z.number().optional().describe('Starting index for results'),
              sort: z
                .enum(['relevance', 'pub_date', 'author', 'journal'])
                .optional()
                .describe('Sort order for results'),
              dateFrom: z.string().optional().describe('Start date filter (YYYY/MM/DD format)'),
              dateTo: z.string().optional().describe('End date filter (YYYY/MM/DD format)(If dateFrom is provided but dateTo is missing, set dateTo to today\'s date)'),
            })
            .optional()
            .describe('Optional search parameters'),
        },
      },
      async ({ query, searchOptions }) => {
        try {
          const options = { ...(searchOptions || {}) };
    
          // If dateFrom is provided but dateTo is missing, set dateTo to today's date
          if (options.dateFrom && !options.dateTo) {
            const now = new Date();
            const yyyy = now.getFullYear();
            const mm = String(now.getMonth() + 1).padStart(2, '0');
            const dd = String(now.getDate()).padStart(2, '0');
            options.dateTo = `${yyyy}/${mm}/${dd}`;
          }
    
          const results = await searchHandler.search(query, options);
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(results, null, 2),
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `Error searching PubMed: ${error instanceof Error ? error.message : 'Unknown error'}`,
              },
            ],
          };
        }
      }
    );
  • Factory function createSearchHandler that initializes PubMed API client and returns a search handler object. The search method calls pubmedApi.searchAndFetch and maps results to {pmid, title, pubDate}.
    export function createSearchHandler(pubmedOptions: PubMedOptions): SearchHandler {
      const pubmedApi = createPubMedAPI(pubmedOptions);
    
      return {
        async search(query: string, searchOptions?: SearchOptions): Promise<SearchResultItem[]> {
          const articles = await pubmedApi.searchAndFetch(query, searchOptions);
          
          return articles.map(article => ({
            pmid: article.pmid,
            title: article.title,
            pubDate: article.pubDate
          }));
        }
      };
    }
  • Core searchAndFetch method in PubMedAPI implementation. Performs ESearch for PMIDs then fetches article details via EFetch, implementing the actual PubMed API interaction for search_pubmed tool.
    const searchAndFetch = async (query: string, options: SearchAndFetchOptions = {}): Promise<Article[]> => {
      const { maxResults = 20, ...searchOptions } = options;
      const searchResult = await search(query, { ...searchOptions, retMax: maxResults });
      return fetchArticles(searchResult.idList);
    };
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states what the tool does but doesn't describe important behaviors like pagination handling (implied by retMax/retStart), rate limits, authentication requirements, error conditions, or what the response format looks like. For a search tool with complex parameters, this is inadequate.

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 that communicates the core purpose without unnecessary words. It's appropriately sized for a search tool and front-loads the essential information.

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?

For a search tool with 2 parameters (one being a complex nested object), no annotations, and no output schema, the description is insufficient. It doesn't explain what the tool returns, how results are structured, or important behavioral aspects like pagination. The agent would need to guess about the response format and operational constraints.

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 fully documents both parameters and their sub-properties. The description adds no parameter-specific information beyond what's in the schema, maintaining the baseline score. It doesn't explain how parameters interact or provide usage examples.

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 ('Search') and resource ('PubMed for scientific articles'), making the purpose immediately understandable. However, it doesn't differentiate this search tool from sibling tools like 'fetch_summary' or 'get_fulltext', which presumably retrieve specific article details rather than perform searches.

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 the sibling tools 'fetch_summary' or 'get_fulltext'. It doesn't mention prerequisites, limitations, or alternative approaches, leaving the agent to infer usage context from tool names alone.

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