Skip to main content
Glama

analyze_memory_patterns

Analyze memory usage patterns to identify trends, extract key insights, and optimize memory management strategies for improved system performance.

Instructions

分析記憶使用模式,提供統計信息和洞察

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
conversation_idYes對話 ID
memory_typeNo分析的記憶類型both
top_keywordsNo返回最常見關鍵詞的數量

Implementation Reference

  • The core handler function for the 'analyze_memory_patterns' tool. It fetches short-term and/or long-term memory managers based on the input parameters and analyzes their memories using the analyzeMemories helper function.
    async handler(args) {
      const { conversation_id, memory_type, top_keywords } = args;
    
      try {
        const analysis = {
          conversation_id,
          timestamp: new Date().toISOString(),
          short_term: null,
          long_term: null
        };
    
        // 分析短期記憶
        if (memory_type === 'short_term' || memory_type === 'both') {
          const manager = await getShortTermManager(conversation_id);
          analysis.short_term = analyzeMemories(manager.getMemories(), top_keywords);
        }
    
        // 分析長期記憶
        if (memory_type === 'long_term' || memory_type === 'both') {
          const manager = await getLongTermManager(conversation_id);
          analysis.long_term = analyzeMemories(manager.getMemories(), top_keywords, true);
        }
    
        return {
          success: true,
          ...analysis
        };
      } catch (error) {
        return {
          success: false,
          error: error.message
        };
      }
    }
  • The Zod input schema defining parameters for the tool: conversation_id (required), memory_type (enum with default 'both'), top_keywords (number default 20).
    inputSchema: z.object({
      conversation_id: z.string().describe('對話 ID'),
      memory_type: z.enum(['short_term', 'long_term', 'both']).default('both').describe('分析的記憶類型'),
      top_keywords: z.number().default(20).describe('返回最常見關鍵詞的數量')
    }),
  • src/index.js:165-166 (registration)
    Registration of search tools (including analyze_memory_patterns) into the toolRegistry with 'search' scope. Note that handlers are dynamically recreated per conversation during execution.
    const searchTools = createSearchTools(getShortTermManager, getLongTermManager);
    searchTools.forEach(tool => registerTool(tool, 'search'));
  • Core helper function that performs statistical analysis on a list of memories: calculates total count, average score, score distribution, top keywords by frequency, and time distribution.
    function analyzeMemories(memories, topN = 20, isLongTerm = false) {
      const total = memories.length;
    
      if (total === 0) {
        return {
          total: 0,
          average_score: 0,
          score_distribution: {},
          top_keywords: [],
          time_distribution: {}
        };
      }
    
      // 計算平均分數
      let totalScore = 0;
      const scoreDistribution = { negative: 0, low: 0, medium: 0, high: 0 };
    
      for (const mem of memories) {
        const score = mem.score || 0;
        totalScore += score;
    
        if (score < 0) scoreDistribution.negative++;
        else if (score < 10) scoreDistribution.low++;
        else if (score < 30) scoreDistribution.medium++;
        else scoreDistribution.high++;
      }
    
      const averageScore = totalScore / total;
    
      // 統計關鍵詞
      const keywordCounts = new Map();
    
      for (const mem of memories) {
        const keywords = mem.keywords || [];
    
        for (const kw of keywords) {
          const word = (kw.word || kw).toLowerCase();
          const weight = kw.weight || 1;
    
          keywordCounts.set(word, (keywordCounts.get(word) || 0) + weight);
        }
      }
    
      // 獲取最常見的關鍵詞
      const topKeywords = Array.from(keywordCounts.entries())
        .sort((a, b) => b[1] - a[1])
        .slice(0, topN)
        .map(([word, count]) => ({ word, count: count.toFixed(2) }));
    
      // 時間分布
      const timeDistribution = analyzeTimeDistribution(memories, isLongTerm);
    
      return {
        total,
        average_score: averageScore.toFixed(2),
        score_distribution: scoreDistribution,
        top_keywords: topKeywords,
        time_distribution: timeDistribution
      };
    }
  • Helper function that categorizes memories into time buckets: last_hour, last_day, last_week, last_month, older based on timestamp.
    function analyzeTimeDistribution(memories, isLongTerm) {
      const now = Date.now();
      const distribution = {
        last_hour: 0,
        last_day: 0,
        last_week: 0,
        last_month: 0,
        older: 0
      };
    
      for (const mem of memories) {
        let timestamp;
    
        if (isLongTerm) {
          timestamp = mem.createdAt ? new Date(mem.createdAt).getTime() : 0;
        } else {
          timestamp = mem.time_stamp ? new Date(mem.time_stamp).getTime() : 0;
        }
    
        const age = now - timestamp;
    
        if (age < 3600000) distribution.last_hour++;
        else if (age < 86400000) distribution.last_day++;
        else if (age < 604800000) distribution.last_week++;
        else if (age < 2592000000) distribution.last_month++;
        else distribution.older++;
      }
    
      return distribution;
    }
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 providing 'statistical information and insights', but doesn't specify what kind of statistics (e.g., frequency, trends), how insights are generated, whether it's a read-only operation, potential performance impacts, or error conditions. For an analysis tool with zero annotation coverage, this leaves significant behavioral gaps.

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 extremely concise and front-loaded: a single sentence in Chinese that directly states the tool's function. There's no wasted verbiage or unnecessary elaboration, making it efficient and easy to parse. Every word contributes to understanding the core purpose.

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 (analyzing memory patterns with 3 parameters), lack of annotations, and no output schema, the description is incomplete. It doesn't cover behavioral aspects like read/write nature, return format, or error handling, and it fails to differentiate from similar sibling tools. For a tool that likely provides detailed analysis results, more context is needed to guide effective use.

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 input schema already documents all parameters (conversation_id, memory_type, top_keywords) with descriptions and defaults. The description adds no additional meaning beyond the schema, such as explaining the purpose of analyzing patterns or how parameters affect the analysis. Baseline 3 is appropriate when the schema handles parameter documentation adequately.

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 tool's purpose: '分析記憶使用模式,提供統計信息和洞察' (analyze memory usage patterns, provide statistical information and insights). It specifies the verb 'analyze' and the resource 'memory usage patterns', which is distinct from sibling tools that focus on adding, deleting, searching, or managing memories. However, it doesn't explicitly differentiate from similar analysis tools like 'get_memory_stats' or 'get_metrics', which slightly reduces clarity.

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 sibling tools like 'get_memory_stats', 'get_metrics', and 'get_cache_stats' that might overlap in functionality, there's no indication of specific contexts, prerequisites, or exclusions. Usage is implied only by the tool's name and description, lacking explicit when/when-not instructions.

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/win10ogod/memory-mcp-server'

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