Skip to main content
Glama
cyqlelabs

MCP Dual-Cycle Reasoner

by cyqlelabs

process_trace_update

Updates and monitors cognitive traces for AI agents by tracking actions, goals, and context, enabling metacognitive analysis with MCP Dual-Cycle Reasoner to detect reasoning loops and optimize decision-making.

Instructions

Process a cognitive trace update from the agent (main monitoring function)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
current_contextNoCurrent environment context or state, in low dash format. Example: adding_product_item
goalYesCurrent goal being pursued
last_actionYesLatest action name to be added to the accumulated action history
window_sizeNoSize of the monitoring window

Implementation Reference

  • The execute function of the process_trace_update tool handler. It validates input using MonitorCognitiveTraceInputSchema, delegates to DualCycleEngine.processTraceUpdate, reports progress, and returns the result as JSON.
    execute: async (args, { log, reportProgress, session }) => {
      try {
        const sessionEngine = this.getSessionEngine(session);
        const sessionId = this.sessionIds.get(session);
        const validatedArgs = MonitorCognitiveTraceInputSchema.parse(args);
    
        log.info('Processing trace update', {
          lastAction: validatedArgs.last_action,
          context: validatedArgs.current_context,
          goal: validatedArgs.goal,
          sessionId,
        });
    
        await reportProgress({ progress: 0, total: 3 });
    
        const result = await sessionEngine.processTraceUpdate(
          validatedArgs.last_action,
          validatedArgs.current_context,
          validatedArgs.goal,
          validatedArgs.window_size
        );
    
        await reportProgress({ progress: 3, total: 3 });
    
        log.info('Trace update processed', {
          loopDetected: result.loop_detected,
          interventionRequired: result.intervention_required,
        });
    
        if (result.loop_detected) {
          result.loop_detected.confidence = parseFloat(
            result.loop_detected.confidence.toFixed(2)
          );
        }
    
        return JSON.stringify(result, null, 2);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        log.error('Failed to process trace update', { error: errorMessage });
        throw new UserError(`Failed to process trace update: ${errorMessage}`);
      }
    },
  • Zod schema for validating inputs to the process_trace_update tool, used in the handler for parsing arguments.
    export const MonitorCognitiveTraceInputSchema = z.object({
      last_action: z.string().describe(DESCRIPTIONS.LAST_ACTION),
      current_context: z.string().optional().describe(DESCRIPTIONS.CURRENT_CONTEXT),
      goal: z.string().describe(DESCRIPTIONS.GOAL),
      window_size: z.number().default(10),
    });
  • src/server.ts:321-385 (registration)
    Registration of the process_trace_update tool via FastMCP server's addTool method within addProcessTraceUpdateTool().
      this.server.addTool({
        name: 'process_trace_update',
        description: 'Process a cognitive trace update from the agent (main monitoring function)',
        parameters: z.object({
          last_action: z.string().describe(DESCRIPTIONS.LAST_ACTION),
          current_context: z
            .string()
            .optional()
            .describe(
              `${DESCRIPTIONS.CURRENT_CONTEXT}, in low dash format. Example: adding_product_item`
            ),
          goal: z.string().describe(DESCRIPTIONS.GOAL),
          window_size: z.number().optional().default(10).describe(DESCRIPTIONS.WINDOW_SIZE),
        }),
        annotations: {
          title: 'Process Cognitive Trace Update',
          readOnlyHint: false,
          destructiveHint: false,
          idempotentHint: false,
          openWorldHint: false,
        },
        execute: async (args, { log, reportProgress, session }) => {
          try {
            const sessionEngine = this.getSessionEngine(session);
            const sessionId = this.sessionIds.get(session);
            const validatedArgs = MonitorCognitiveTraceInputSchema.parse(args);
    
            log.info('Processing trace update', {
              lastAction: validatedArgs.last_action,
              context: validatedArgs.current_context,
              goal: validatedArgs.goal,
              sessionId,
            });
    
            await reportProgress({ progress: 0, total: 3 });
    
            const result = await sessionEngine.processTraceUpdate(
              validatedArgs.last_action,
              validatedArgs.current_context,
              validatedArgs.goal,
              validatedArgs.window_size
            );
    
            await reportProgress({ progress: 3, total: 3 });
    
            log.info('Trace update processed', {
              loopDetected: result.loop_detected,
              interventionRequired: result.intervention_required,
            });
    
            if (result.loop_detected) {
              result.loop_detected.confidence = parseFloat(
                result.loop_detected.confidence.toFixed(2)
              );
            }
    
            return JSON.stringify(result, null, 2);
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            log.error('Failed to process trace update', { error: errorMessage });
            throw new UserError(`Failed to process trace update: ${errorMessage}`);
          }
        },
      });
    }
  • Core helper method in DualCycleEngine that implements the metacognitive monitoring logic: accumulates actions, detects loops via sentinel.detectLoop, and determines if intervention is required.
    async processTraceUpdate(
      lastAction: string,
      currentContext?: string,
      goal?: string,
      windowSize?: number
    ): Promise<{
      intervention_required: boolean;
      loop_detected?: LoopDetectionResult;
      explanation?: string;
    }> {
      if (!this.isMonitoring) {
        return { intervention_required: false };
      }
    
      // Add the new action to the accumulated actions
      this.accumulatedActions.push(lastAction);
      this.currentTrace.last_action = lastAction;
    
      console.log(
        `šŸ” DEBUG: Added action "${lastAction}" to accumulated actions. Total: ${this.accumulatedActions.length}`
      );
    
      // Update other trace properties if provided
      if (currentContext) {
        this.currentTrace.current_context = currentContext;
      }
      if (goal) {
        this.currentTrace.goal = goal;
      }
    
      console.log(
        chalk.gray(
          `\nšŸ“Š Processing trace update: Added "${lastAction}" (${this.accumulatedActions.length} total actions)`
        )
      );
    
      // METACOGNITIVE CYCLE - Phase 1: MONITOR
      const loopDetection = await this.monitorForLoops(this.currentTrace, windowSize ?? 10);
    
      if (!loopDetection.detected) {
        console.log(chalk.green('āœ… No loops detected - cognitive cycle proceeding normally'));
        return {
          intervention_required: false,
          loop_detected: loopDetection,
        };
      }
    
      console.log(
        chalk.yellow(
          `āš ļø  Loop detected: ${loopDetection.type} (confidence: ${(loopDetection.confidence * 100).toFixed(1)}%)`
        )
      );
      console.log(chalk.yellow(`   Details: ${loopDetection.details}`));
    
      this.interventionCount++;
    
      const explanation = this.generateInterventionExplanation(loopDetection);
    
      console.log(chalk.cyan(`\nšŸ’” Intervention #${this.interventionCount}: ${explanation}`));
    
      return {
        intervention_required: true,
        loop_detected: loopDetection,
        explanation,
      };
    }
Behavior3/5

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

Annotations provide basic hints (non-readOnly, non-openWorld, non-idempotent, non-destructive), but the description adds minimal behavioral context beyond this. It mentions this is for 'main monitoring function' which suggests it might be part of a monitoring system, but doesn't explain what 'processing' entails, whether it triggers side effects, or how it interacts with the monitoring state. No contradiction with annotations exists, but the description doesn't significantly enhance understanding of the tool's behavior.

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 a single, concise sentence that gets straight to the point without unnecessary words. It's front-loaded with the core action ('Process a cognitive trace update') and adds clarifying context ('from the agent (main monitoring function)'). While efficient, it could be slightly more informative without losing conciseness.

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

Completeness3/5

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

Given the tool has no output schema and annotations cover basic hints, the description provides minimal but adequate context for a processing function. It identifies the tool as part of monitoring, but doesn't explain what 'cognitive trace' is, what the update does, or what the expected outcomes are. For a tool with 4 parameters and no output schema, more detail on behavior and results would improve completeness, but it's not entirely inadequate.

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%, with clear descriptions for all 4 parameters (current_context, goal, last_action, window_size). The description adds no parameter-specific information beyond what the schema provides, such as explaining relationships between parameters or usage examples. With high schema coverage, the baseline score of 3 is appropriate as the description doesn't compensate but doesn't need to given the schema's completeness.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

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

The description states the tool 'Process a cognitive trace update from the agent' which provides a general purpose (processing updates) but lacks specificity about what 'cognitive trace' means or what resources are involved. It mentions 'main monitoring function' which adds some context but doesn't clearly distinguish this from sibling monitoring tools like 'start_monitoring', 'stop_monitoring', or 'get_monitoring_status'. The purpose is understandable but vague compared to what could be achieved.

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 siblings like 'detect_loop', 'retrieve_similar_cases', and 'store_experience' that might handle related cognitive or monitoring functions, there's no indication of when this specific update processing is appropriate versus other tools. The phrase 'main monitoring function' implies a central role but doesn't specify context or exclusions.

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

Related 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/cyqlelabs/mcp-dual-cycle-reasoner'

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