Skip to main content
Glama
stat-guy

Chain of Draft (CoD) MCP Server

by stat-guy

logic_solve

Solve logic problems using Chain of Draft reasoning to generate minimal intermediate steps while maintaining accuracy.

Instructions

Solve a logic problem using Chain of Draft reasoning

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
problemYesThe logic problem to solve
approachNoForce 'CoD' or 'CoT' approach
max_words_per_stepNoMaximum words per reasoning step

Implementation Reference

  • Handler for the 'logic_solve' tool in the MCP callTool request handler. Invokes the core Chain of Draft reasoning client with domain set to 'logic' and formats the response.
    if (name === "logic_solve") {
      const result = await chainOfDraftClient.solveWithReasoning({
        ...args,
        domain: "logic"
      });
      
      const formattedResponse = 
        `Chain of ${result.approach} reasoning (${result.word_limit} word limit):\n\n` +
        `${result.reasoning_steps}\n\n` +
        `Final answer: ${result.final_answer}\n\n` +
        `Stats: ${result.token_count} tokens, ${result.execution_time_ms.toFixed(0)}ms, ` +
        `complexity score: ${result.complexity}`;
      
      return {
        content: [{
          type: "text",
          text: formattedResponse
        }]
      };
    }
  • Input schema definition for the logic_solve tool, used in tool listing.
    const LOGIC_TOOL = {
      name: "logic_solve",
      description: "Solve a logic problem using Chain of Draft reasoning",
      inputSchema: {
        type: "object",
        properties: {
          problem: {
            type: "string",
            description: "The logic problem to solve"
          },
          approach: {
            type: "string",
            description: "Force 'CoD' or 'CoT' approach"
          },
          max_words_per_step: {
            type: "number",
            description: "Maximum words per reasoning step"
          }
        },
        required: ["problem"]
      }
    };
  • Handler function for logic_solve tool in FastMCP server. Registered via @app.tool() decorator (which infers schema from parameters). Delegates to chain_of_draft_solve with domain='logic'.
    @app.tool()
    async def logic_solve(
        problem: str,
        approach: str = None,
        max_words_per_step: int = None
    ) -> str:
        """Solve a logic problem using Chain of Draft reasoning.
        
        Args:
            problem: The logic problem to solve
            approach: Force "CoD" or "CoT" approach (default: auto-select)
            max_words_per_step: Maximum words per step (default: adaptive)
        """
        return await chain_of_draft_solve(
            problem=problem,
            domain="logic",
            approach=approach,
            max_words_per_step=max_words_per_step
        )
  • Core ChainOfDraftClient.solveWithReasoning helper implementing the reasoning logic (complexity estimation, approach selection CoD/CoT, prompt creation, Anthropic Claude API call, response extraction, format enforcement, analytics logging). Used by all domain tools including logic_solve.
    async solveWithReasoning(params) {
      const {
        problem,
        domain = 'general',
        max_words_per_step = null,
        approach = null,
        enforce_format = true,
        adaptive_word_limit = true
      } = params;
      
      const startTime = Date.now();
      
      // Analyze problem complexity
      const analysis = complexityEstimator.analyzeProblem(problem, domain);
      const complexity = analysis.estimated_complexity;
      
      // Determine word limit
      let wordLimit = max_words_per_step;
      if (!wordLimit && adaptive_word_limit) {
        wordLimit = complexity;
      } else if (!wordLimit) {
        // Default based on domain
        wordLimit = complexityEstimator.domainBaseLimits[domain] || 5;
      }
      
      // Determine approach (CoD or CoT)
      const performanceStats = analyticsDb.getPerformanceByDomain(domain);
      const selectedApproach = approach || 
        reasoningSelector.selectApproach(domain, complexity, performanceStats);
      
      // Create prompt based on approach
      const prompt = selectedApproach === 'CoD' 
        ? createCodPrompt(problem, domain, [], wordLimit)
        : createCotPrompt(problem, domain, []);
      
      // Call Claude
      const response = await anthropic.messages.create({
        model: 'claude-3-sonnet-20240229',
        max_tokens: 1000,
        messages: [
          { role: 'user', content: prompt }
        ]
      });
      
      // Extract reasoning and answer
      const fullText = response.content[0].text;
      
      // Extract final answer (assuming it comes after the reasoning, often starts with "Answer:" or similar)
      let reasoningSteps = fullText;
      let finalAnswer = '';
      
      // Common patterns for final answer sections
      const answerPatterns = [
        /(?:Final Answer|Answer|Therefore):?\s*(.*?)$/is,
        /(?:In conclusion|To conclude|Thus|Hence|So),\s*(.*?)$/is,
        /(?:The answer is|The result is|The solution is)\s*(.*?)$/is
      ];
      
      // Try to extract the final answer with each pattern
      for (const pattern of answerPatterns) {
        const match = fullText.match(pattern);
        if (match && match[1]) {
          finalAnswer = match[1].trim();
          reasoningSteps = fullText.substring(0, fullText.indexOf(match[0])).trim();
          break;
        }
      }
      
      // If no pattern matched, just use the last sentence
      if (!finalAnswer) {
        const sentences = fullText.split(/[.!?]+\s+/);
        if (sentences.length > 1) {
          finalAnswer = sentences.pop().trim();
          reasoningSteps = sentences.join('. ') + '.';
        }
      }
      
      // Apply format enforcement if needed
      if (enforce_format && selectedApproach === 'CoD') {
        reasoningSteps = formatEnforcer.enforceWordLimit(reasoningSteps, wordLimit);
      }
      
      // Calculate execution time
      const executionTime = Date.now() - startTime;
      
      // Estimate token count (rough approximation)
      const tokenCount = Math.ceil(fullText.length / 4);
      
      // Record analytics
      analyticsDb.addRecord({
        problem_id: problem.substring(0, 20),
        problem_text: problem,
        domain,
        approach: selectedApproach,
        word_limit: wordLimit,
        tokens_used: tokenCount,
        execution_time_ms: executionTime,
        reasoning_steps: reasoningSteps,
        answer: finalAnswer
      });
      
      // Return result
      return {
        approach: selectedApproach,
        reasoning_steps: reasoningSteps,
        final_answer: finalAnswer,
        token_count: tokenCount,
        word_limit: wordLimit,
        complexity: complexity,
        execution_time_ms: executionTime
      };
    }

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/stat-guy/chain-of-draft'

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