Skip to main content
Glama

run_self_distill

Destructive

Analyzes recent agent conversations to detect success or failure signals, then generates and persists improvement lessons that prevent future mistakes without human feedback.

Instructions

Run the self-distillation agent to auto-evaluate recent agent sessions and generate improvement lessons without human feedback. Reads conversation logs, detects success/failure signals, and persists lessons.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dryRunNoIf true, analyzes but does not persist lessons
limitNoMax conversation logs to process (default 20)
modelNoLLM model to use for analysis (requires ANTHROPIC_API_KEY)

Implementation Reference

  • Main handler function for the run_self_distill tool. Reads conversation logs, detects outcome signals (errors, test failures, corrections, successes), classifies outcomes as positive/negative/neutral, generates lessons (heuristically or via LLM), persists them as lessons, and returns a manifest.
    async function runSelfDistill({ dryRun = false, limit = 20, model } = {}) {
      const startedAt = new Date().toISOString();
      const logPaths = discoverConversationLogs({ limit });
      const hasApiKey = Boolean(process.env.ANTHROPIC_API_KEY);
      const analysisMode = hasApiKey ? 'llm' : 'heuristic';
    
      const allLessons = [];
      let sessionsProcessed = 0;
      let sessionsSkipped = 0;
    
      for (const logPath of logPaths) {
        const entries = readJsonl(logPath);
        if (entries.length === 0) {
          sessionsSkipped++;
          continue;
        }
    
        // Treat each log file as one conversation session
        const conversationWindow = entries.slice(-30); // last 30 messages max
        const signals = detectOutcomeSignals(conversationWindow);
        const outcome = classifyOutcome(signals);
    
        if (outcome === 'neutral') {
          sessionsSkipped++;
          continue;
        }
    
        sessionsProcessed++;
    
        let lessons;
        if (hasApiKey) {
          lessons = await generateLlmLessons(conversationWindow, model);
          // Fall back to heuristic if LLM returns nothing
          if (!lessons || lessons.length === 0) {
            lessons = generateHeuristicLessons(conversationWindow, signals);
          }
        } else {
          lessons = generateHeuristicLessons(conversationWindow, signals);
        }
    
        for (const lesson of lessons) {
          if (!dryRun) {
            createLesson({
              feedbackId: null,
              signal: lesson.signal,
              inferredLesson: lesson.action.description,
              triggerMessage: lesson.trigger.condition,
              priorSummary: lesson.evidence || '',
              confidence: Math.round((lesson.confidence || 0.5) * 100),
              tags: ['self-distill', lesson.signal],
              metadata: {
                source: 'self-distill-agent',
                analysisMode,
                triggerType: lesson.trigger.type,
                actionType: lesson.action.type,
                logPath,
              },
            });
          }
          allLessons.push(lesson);
        }
      }
    
      const manifest = {
        id: buildStableId('distill'),
        startedAt,
        completedAt: new Date().toISOString(),
        dryRun,
        analysisMode,
        sessionsProcessed,
        sessionsSkipped,
        lessonsGenerated: allLessons.length,
        logPaths,
        lessons: allLessons.map((l) => ({
          signal: l.signal,
          trigger: l.trigger,
          action: l.action,
          confidence: l.confidence,
        })),
      };
    
      if (!dryRun) {
        writeRunManifest(manifest);
      }
    
      return manifest;
    }
  • MCP tool registration — maps 'run_self_distill' string to a require() of the self-distill-agent module, calling runSelfDistill with dryRun, limit, and model args from the MCP request.
    case 'run_self_distill': {
      const { runSelfDistill } = require('../../scripts/self-distill-agent');
      return toTextResult(await runSelfDistill({ dryRun: args.dryRun, limit: args.limit, model: args.model }));
    }
  • getSelfDistillStatus helper — reads persisted run manifests and returns summary of last run and total stats. Exported and callable via the companion 'self_distill_status' MCP tool.
    function getSelfDistillStatus() {
      const runs = readRunManifests();
      if (runs.length === 0) return null;
    
      const lastRun = runs[runs.length - 1];
      return {
        lastRunId: lastRun.id,
        lastRunAt: lastRun.completedAt,
        totalRuns: runs.length,
        totalLessons: runs.reduce((sum, r) => sum + (r.lessonsGenerated || 0), 0),
        lastAnalysisMode: lastRun.analysisMode,
        lastSessionsProcessed: lastRun.sessionsProcessed,
        lastLessonsGenerated: lastRun.lessonsGenerated,
      };
    }
  • Module exports — runSelfDistill, getSelfDistillStatus, detectOutcomeSignals, discoverConversationLogs, classifyOutcome, generateHeuristicLessons, and SELF_DISTILL_RUNS_PATH are publicly exposed.
    module.exports = {
      runSelfDistill,
      getSelfDistillStatus,
      detectOutcomeSignals,
      discoverConversationLogs,
      classifyOutcome,
      generateHeuristicLessons,
      SELF_DISTILL_RUNS_PATH,
    };
Behavior3/5

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

Annotations include destructiveHint=true, and the description states it 'persists lessons', confirming mutation. It also reveals it reads conversation logs and detects signals. However, it does not elaborate on what gets destroyed or overwritten, nor does it describe error handling or side effects beyond the persistence. The description adds moderate behavioral context beyond the annotation.

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 two sentences, front-loaded with the primary action ('Run the self-distillation agent'). Every sentence adds necessary information without redundancy. It is appropriately concise and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (3 parameters, no output schema, destructive hint), the description is fairly complete. It explains the purpose, inputs (logs), process (detect signals), and output (persist lessons). However, it lacks details on return values or error states, which would be helpful for a mutation tool. Still, it covers the core functionality well.

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 input schema has 3 parameters with 100% description coverage, so the schema already documents each parameter well. The description does not add additional meaning or usage examples for the parameters, such as default values or interaction effects. Therefore, the description provides minimal added value for parameter understanding.

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 what the tool does: runs a self-distillation agent to auto-evaluate recent agent sessions and generate improvement lessons. It specifies the verb 'run', the resource 'self_distillation agent', and the outcome 'generate improvement lessons'. This distinguishes it from sibling tools like retrieve_lessons or infer_lesson_from_history.

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 does not provide explicit guidance on when to use this tool versus alternatives. It mentions 'without human feedback', implying it's for automated evaluation, but does not specify prerequisites, when not to use, or which sibling tools serve as alternatives (e.g., infer_lesson_from_history).

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/IgorGanapolsky/ThumbGate'

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