Skip to main content
Glama
Aki894
by Aki894

ae_pipeline_rag

Analyze adverse events in clinical trials by retrieving, processing, and summarizing safety data to answer drug safety queries.

Instructions

Advanced RAG pipeline for adverse events analysis. Fetches, extracts, chunks, retrieves and summarizes clinical trial data in one call to prevent LLM response truncation.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNoNatural language query about adverse events. Example: 'gastrointestinal bleeding risk vs placebo'
drugNoDrug name to focus the analysis on. Example: 'Vemurafenib'
conditionNoMedical condition context. Example: 'melanoma', 'cancer'
top_kNoNumber of most relevant text chunks to return (1-10)
filtersNoAdditional filters for data retrieval

Implementation Reference

  • The `aePipelineRag` method handles the full RAG pipeline logic for adverse events, including data fetching, chunking, keyword retrieval, and summary generation.
    private async aePipelineRag(params: AEPipelineRAGParams): Promise<{ content: Array<{ type: string; text: string }> }> {
      try {
        // 1. 构建搜索参数
        const searchParams: ClinicalTrialSearchParams = {
          pageSize: params.filters?.limit || 50,
          countTotal: true
        };
    
        if (params.drug) searchParams.intervention = params.drug;
        if (params.condition) searchParams.condition = params.condition;
        if (params.filters?.status) searchParams.status = params.filters.status;
        if (params.filters?.include_completed_only) {
          searchParams.status = "COMPLETED";
        }
    
        // 2. 抓取数据
        const data = await this.makeRequest(searchParams);
        
        if (!data.studies || data.studies.length === 0) {
          const result: RAGResult = {
            source: "clinicaltrials",
            query: params.query,
            drug: params.drug,
            condition: params.condition,
            top_chunks: [],
            summary: "未找到匹配的临床试验数据。请尝试调整搜索条件。",
            citations: []
          };
          
          return {
            content: [{
              type: "text",
              text: JSON.stringify(result, null, 2)
            }]
          };
        }
    
        // 3. 提取和分块文本
        const allChunks: TextChunk[] = [];
        
        for (const study of data.studies) {
          const studyText = this.extractStudyText(study);
          if (studyText.trim().length > 0) {
            const nctId = study.protocolSection?.identificationModule?.nctId || 'unknown';
            const title = study.protocolSection?.identificationModule?.briefTitle || 'Untitled Study';
            
            const chunks = chunkText(
              studyText,
              1000,
              200,
              nctId,
              {
                title,
                type: 'clinical_trial',
                hasResults: !!study.resultsSection,
                hasAdverseEvents: !!study.resultsSection?.adverseEventsModule
              }
            );
            
            allChunks.push(...chunks);
          }
        }
    
        // 4. 构建查询关键词
        const queryText = [params.query, params.drug, params.condition]
          .filter(Boolean)
          .join(' ');
        
        const extraKeywords = [
          'adverse events', 'side effects', 'safety', 'toxicity',
          'placebo', 'control', 'comparison', 'risk',
          '不良事件', '副作用', '安全性', '对照'
        ];
    
        // 5. 检索和排序
        const topChunks = rankAndPickTop(
          allChunks,
          queryText,
          params.top_k,
          extraKeywords
        );
    
        // 6. 生成摘要
        const summary = summarizeChunks(topChunks, {
          source: 'clinicaltrials',
          query: params.query,
          drug: params.drug,
          condition: params.condition,
          maxLength: 1200
        });
    
        // 7. 提取引用
        const citations = extractCitations(topChunks);
    
        // 8. 构建结果
        const result: RAGResult = {
          source: "clinicaltrials",
          query: params.query,
          drug: params.drug,
          condition: params.condition,
          top_chunks: topChunks.map(chunk => ({
            ...chunk,
            text: chunk.text.length > 1200 ? chunk.text.slice(0, 1200) + '...' : chunk.text
          })),
          summary,
          citations
        };
    
        return {
          content: [{
            type: "text",
            text: JSON.stringify(result, null, 2)
          }]
        };
  • The `AEPipelineRAGParamsSchema` Zod schema defines the input parameters for the `ae_pipeline_rag` tool.
    const AEPipelineRAGParamsSchema = z.object({
      query: z.string().optional(),
      drug: z.string().optional(),
      condition: z.string().optional(),
      top_k: z.coerce.number().int().min(1).max(10).optional().default(5),
      filters: z.object({
        status: z.string().optional().default("COMPLETED"),
        limit: z.coerce.number().int().min(1).max(100).optional().default(50),
        include_completed_only: z.boolean().optional().default(true)
      }).optional().default({})
    });
  • src/index.ts:197-247 (registration)
    The tool `ae_pipeline_rag` is defined in the `ListToolsRequestSchema` response.
    {
      name: "ae_pipeline_rag",
      description: "Advanced RAG pipeline for adverse events analysis. Fetches, extracts, chunks, retrieves and summarizes clinical trial data in one call to prevent LLM response truncation.",
      inputSchema: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description: "Natural language query about adverse events. Example: 'gastrointestinal bleeding risk vs placebo'"
          },
          drug: {
            type: "string",
            description: "Drug name to focus the analysis on. Example: 'Vemurafenib'"
          },
          condition: {
            type: "string",
            description: "Medical condition context. Example: 'melanoma', 'cancer'"
          },
          top_k: {
            type: "number",
            description: "Number of most relevant text chunks to return (1-10)",
            default: 5,
            minimum: 1,
            maximum: 10
          },
          filters: {
            type: "object",
            description: "Additional filters for data retrieval",
            properties: {
              status: {
                type: "string",
                description: "Study status filter",
                default: "COMPLETED"
              },
              limit: {
                type: "number",
                description: "Maximum studies to fetch",
                default: 50,
                minimum: 1,
                maximum: 100
              },
              include_completed_only: {
                type: "boolean",
                description: "Only include completed studies with results",
                default: true
              }
            }
          }
        }
      }
    },
  • src/index.ts:322-324 (registration)
    The `ae_pipeline_rag` tool request is handled in the `CallToolRequestSchema` switch statement, which calls `this.aePipelineRag`.
    case "ae_pipeline_rag":
      const ragParams = AEPipelineRAGParamsSchema.parse(args);
      return await this.aePipelineRag(ragParams);
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 of behavioral disclosure. It mentions the tool performs multiple steps 'in one call' to prevent truncation, which is useful context, but lacks critical details like whether it's read-only or mutative, what permissions are needed, rate limits, error handling, or what the output looks like. For a complex pipeline tool with zero 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.

Conciseness4/5

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

The description is appropriately sized and front-loaded, with the first sentence stating the core purpose and the second explaining the key benefit ('in one call to prevent LLM response truncation'). Every sentence earns its place, though it could be slightly more concise by combining ideas.

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 tool's complexity (a multi-step RAG pipeline), lack of annotations, and no output schema, the description is incomplete. It doesn't cover behavioral aspects like safety, performance, or output format, leaving significant gaps for an AI agent to understand how to invoke it correctly and interpret results.

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 already documents all 5 parameters thoroughly. The description doesn't add any parameter-specific semantics beyond what's in the schema (e.g., it doesn't explain how parameters interact or provide additional examples). 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.

Purpose5/5

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

The description clearly states the tool's purpose with specific verbs ('fetches, extracts, chunks, retrieves and summarizes') and resource ('clinical trial data'), and distinguishes it from siblings by emphasizing it's an 'Advanced RAG pipeline for adverse events analysis' that handles everything 'in one call to prevent LLM response truncation'—unlike the more focused sibling tools.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool ('for adverse events analysis' and 'to prevent LLM response truncation'), implying it's a comprehensive alternative to multiple calls. However, it doesn't explicitly state when not to use it or name specific sibling alternatives for comparison, which would elevate it to a 5.

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/Aki894/mcp-ClinicalTrial'

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