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,
      };
    }
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