Skip to main content
Glama
flyanima

Open Search MCP

by flyanima

search_pubmed

Search PubMed to find medical and life science literature using customizable filters for publication type, date range, and sorting options.

Instructions

Search PubMed for medical and life science literature

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query for medical literature (e.g., "COVID-19 treatment", "cancer immunotherapy", "diabetes management")
maxResultsNoMaximum number of articles to return (1-200)
sortNoSort order: relevance, daterelevance
publicationTypeNoFilter by publication type: all, review, clinical_trial, meta_analysis, case_reportall
dateRangeNoDate range filter: all, 1year, 5years, 10yearsall

Implementation Reference

  • The main handler function that executes the search_pubmed tool. It processes input arguments, calls the PubMedAPIClient's searchPubMed method, handles the API response, and returns formatted results or error information.
    execute: async (args: any) => {
      const { query, maxResults = 20, sort = 'relevance', publicationType = 'all', dateRange = 'all' } = args;
    
      try {
        const startTime = Date.now();
    
        // 使用真正的PubMed API
        const result = await client.searchPubMed(query, {
          maxResults,
          sort,
          publicationType,
          dateRange
        });
    
        const searchTime = Date.now() - startTime;
    
        return {
          success: true,
          data: {
            source: 'PubMed API',
            query,
            sort,
            publicationType,
            dateRange,
            totalResults: result.count,
            articles: result.articles,
            searchTime,
            timestamp: Date.now(),
            apiUsed: true,
            searchMetadata: {
              database: 'PubMed',
              searchStrategy: 'E-utilities API',
              filters: {
                publicationType: publicationType !== 'all' ? publicationType : null,
                dateRange: dateRange !== 'all' ? dateRange : null,
                sort
              }
            }
          }
        };
      } catch (error) {
        // 如果API失败,提供有用的错误信息
        return {
          success: false,
          error: `PubMed search failed: ${error instanceof Error ? error.message : String(error)}`,
          data: {
            source: 'PubMed',
            query,
            articles: [],
            totalResults: 0,
            apiUsed: false,
            suggestions: [
              'Check your internet connection',
              'Try simpler search terms',
              'Use medical subject headings (MeSH terms)',
              'Try again in a few moments'
            ]
          }
        };
      }
    }
  • Input schema defining the parameters for the search_pubmed tool: query (required), maxResults, sort, publicationType, and dateRange.
    inputSchema: {
      type: 'object',
      properties: {
        query: {
          type: 'string',
          description: 'Search query for medical literature (e.g., "COVID-19 treatment", "cancer immunotherapy", "diabetes management")'
        },
        maxResults: {
          type: 'number',
          description: 'Maximum number of articles to return (1-200)',
          default: 20,
          minimum: 1,
          maximum: 200
        },
        sort: {
          type: 'string',
          description: 'Sort order: relevance, date',
          default: 'relevance',
          enum: ['relevance', 'date']
        },
        publicationType: {
          type: 'string',
          description: 'Filter by publication type: all, review, clinical_trial, meta_analysis, case_report',
          default: 'all',
          enum: ['all', 'review', 'clinical_trial', 'meta_analysis', 'case_report']
        },
        dateRange: {
          type: 'string',
          description: 'Date range filter: all, 1year, 5years, 10years',
          default: 'all',
          enum: ['all', '1year', '5years', '10years']
        }
      },
      required: ['query']
    },
  • Registration of the search_pubmed tool in the registerPubMedTools function, specifying name, description, category, source, inputSchema, and execute handler.
    registry.registerTool({
      name: 'search_pubmed',
      description: 'Search PubMed for medical and life science literature',
      category: 'academic',
      source: 'PubMed',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'Search query for medical literature (e.g., "COVID-19 treatment", "cancer immunotherapy", "diabetes management")'
          },
          maxResults: {
            type: 'number',
            description: 'Maximum number of articles to return (1-200)',
            default: 20,
            minimum: 1,
            maximum: 200
          },
          sort: {
            type: 'string',
            description: 'Sort order: relevance, date',
            default: 'relevance',
            enum: ['relevance', 'date']
          },
          publicationType: {
            type: 'string',
            description: 'Filter by publication type: all, review, clinical_trial, meta_analysis, case_report',
            default: 'all',
            enum: ['all', 'review', 'clinical_trial', 'meta_analysis', 'case_report']
          },
          dateRange: {
            type: 'string',
            description: 'Date range filter: all, 1year, 5years, 10years',
            default: 'all',
            enum: ['all', '1year', '5years', '10years']
          }
        },
        required: ['query']
      },
      execute: async (args: any) => {
        const { query, maxResults = 20, sort = 'relevance', publicationType = 'all', dateRange = 'all' } = args;
    
        try {
          const startTime = Date.now();
    
          // 使用真正的PubMed API
          const result = await client.searchPubMed(query, {
            maxResults,
            sort,
            publicationType,
            dateRange
          });
    
          const searchTime = Date.now() - startTime;
    
          return {
            success: true,
            data: {
              source: 'PubMed API',
              query,
              sort,
              publicationType,
              dateRange,
              totalResults: result.count,
              articles: result.articles,
              searchTime,
              timestamp: Date.now(),
              apiUsed: true,
              searchMetadata: {
                database: 'PubMed',
                searchStrategy: 'E-utilities API',
                filters: {
                  publicationType: publicationType !== 'all' ? publicationType : null,
                  dateRange: dateRange !== 'all' ? dateRange : null,
                  sort
                }
              }
            }
          };
        } catch (error) {
          // 如果API失败,提供有用的错误信息
          return {
            success: false,
            error: `PubMed search failed: ${error instanceof Error ? error.message : String(error)}`,
            data: {
              source: 'PubMed',
              query,
              articles: [],
              totalResults: 0,
              apiUsed: false,
              suggestions: [
                'Check your internet connection',
                'Try simpler search terms',
                'Use medical subject headings (MeSH terms)',
                'Try again in a few moments'
              ]
            }
          };
        }
      }
    });
  • Core helper method in PubMedAPIClient that handles PubMed ESearch and ESummary API calls to retrieve article search results.
    async searchPubMed(query: string, options: any = {}) {
      // 第一步:搜索获取PMID列表
      const searchParams = {
        db: 'pubmed',
        term: query,
        retmax: options.maxResults || 20,
        sort: options.sort === 'date' ? 'pub_date' : 'relevance',
        datetype: 'pdat'
      };
    
      // 添加日期过滤
      if (options.dateRange && options.dateRange !== 'all') {
        const now = new Date();
        let startDate;
    
        switch (options.dateRange) {
          case '1year':
            startDate = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
            break;
          case '5years':
            startDate = new Date(now.getFullYear() - 5, now.getMonth(), now.getDate());
            break;
          case '10years':
            startDate = new Date(now.getFullYear() - 10, now.getMonth(), now.getDate());
            break;
        }
    
        if (startDate) {
          const startDateStr = startDate.toISOString().split('T')[0].replace(/-/g, '/');
          const endDateStr = now.toISOString().split('T')[0].replace(/-/g, '/');
          searchParams.term += ` AND ("${startDateStr}"[Date - Publication] : "${endDateStr}"[Date - Publication])`;
        }
      }
    
      // 添加出版物类型过滤
      if (options.publicationType && options.publicationType !== 'all') {
        const typeMap: Record<string, string> = {
          'review': 'Review[Publication Type]',
          'clinical_trial': 'Clinical Trial[Publication Type]',
          'meta_analysis': 'Meta-Analysis[Publication Type]',
          'case_report': 'Case Reports[Publication Type]'
        };
    
        const pubType = options.publicationType as string;
        if (typeMap[pubType]) {
          searchParams.term += ` AND ${typeMap[pubType]}`;
        }
      }
    
      const searchResult = await this.makeRequest('esearch.fcgi', searchParams);
    
      if (!searchResult.esearchresult || !searchResult.esearchresult.idlist || searchResult.esearchresult.idlist.length === 0) {
        return { articles: [], count: 0 };
      }
    
      const pmids = searchResult.esearchresult.idlist;
    
      // 第二步:获取详细信息
      const summaryParams = {
        db: 'pubmed',
        id: pmids.join(','),
        retmode: 'json'
      };
    
      const summaryResult = await this.makeRequest('esummary.fcgi', summaryParams);
    
      return {
        articles: this.parseSummaryResult(summaryResult),
        count: parseInt(searchResult.esearchresult.count) || 0
      };
    }
  • src/index.ts:230-230 (registration)
    Top-level registration call in the main server initialization that invokes registerPubMedTools to add search_pubmed to the tool registry.
    registerPubMedTools(this.toolRegistry);             // 1 tool: search_pubmed
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. While 'Search' implies a read-only operation, it doesn't mention rate limits, authentication requirements, pagination behavior, or what format the results will be in (since no output schema exists). This leaves significant gaps for an agent to understand how to interact with the tool effectively.

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, clear sentence with zero wasted words. It's front-loaded with the core purpose and efficiently communicates the essential information without unnecessary elaboration.

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 5 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the tool returns (article metadata, abstracts, full text links?), how results are formatted, or any behavioral constraints. The high parameter count and lack of structured output information mean the description should do more to guide usage.

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 description adds no parameter information beyond what's already in the schema, which has 100% coverage with detailed descriptions, defaults, enums, and constraints. This meets the baseline of 3 since the schema does all the heavy lifting, but the description doesn't provide additional context about how parameters interact or typical usage patterns.

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 verb ('Search') and resource ('PubMed for medical and life science literature'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'search_arxiv' or 'search_semantic_scholar' beyond mentioning PubMed specifically, which is why it doesn't reach the highest score.

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. With many sibling search tools available (e.g., search_arxiv, search_semantic_scholar, search_ieee), there's no indication of PubMed's specific domain (medical/life sciences) or when it might be preferred over other research databases.

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/flyanima/open-search-mcp'

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