Skip to main content
Glama
kingdomseed

Structured Workflow MCP

by kingdomseed

build_custom_workflow

Create structured development workflows by selecting phases, setting iteration limits, and configuring outputs for programming tasks. Enforces disciplined practices through audit and verification at each phase.

Instructions

Build a custom workflow with full control over phases and configuration. Use specific workflow tools (refactor_workflow, create_feature_workflow, etc.) for optimized presets.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
taskYesDescription of the programming task
workflowTypeNoUse a predefined workflow type or custom for full controlcustom
selectedPhasesNoSelect which phases to include in your workflow
iterationLimitsNoSet iteration limits before escalation to user input
outputPreferencesNo
userCheckpointsNo

Implementation Reference

  • handleBuildCustomWorkflow: Primary exported handler for the 'build_custom_workflow' tool. Processes input parameters, detects optimal workflow type and suggests alternatives if applicable, applies presets, and invokes the core implementation.
    export async function handleBuildCustomWorkflow(
      params: {
        task: string;
        workflowType?: WorkflowType | 'custom';
        selectedPhases?: Phase[];
        iterationLimits?: any;
        outputPreferences?: any;
        userCheckpoints?: any;
      },
      sessionManager: SessionManager
    ) {
      // Detect workflow type if not specified
      const detectedType = params.workflowType === 'custom' ? null : params.workflowType || detectWorkflowType(params.task);
      
      // If a workflow type is detected, suggest using the specific tool
      if (detectedType && !params.workflowType) {
        const workflowTools = {
          refactor: 'refactor_workflow',
          feature: 'create_feature_workflow',
          test: 'test_workflow',
          tdd: 'tdd_workflow'
        };
        
        return {
          suggestion: `Based on your task description, consider using ${workflowTools[detectedType]} for an optimized ${detectedType} workflow`,
          detectedType,
          alternativeCommand: `${workflowTools[detectedType]}({ task: "${params.task}" })`,
          proceedingWithCustom: 'Proceeding with custom workflow configuration...',
          customWorkflow: await buildCustomWorkflowImplementation(params, sessionManager)
        };
      }
      
      // Use preset if workflow type is specified
      if (params.workflowType && params.workflowType !== 'custom') {
        const preset = getWorkflowPreset(params.workflowType);
        params.selectedPhases = params.selectedPhases || preset.phases;
        params.iterationLimits = { ...preset.iterationLimits, ...params.iterationLimits };
      }
      
      return buildCustomWorkflowImplementation(params, sessionManager);
    }
  • buildCustomWorkflowImplementation: Core execution logic for building custom workflows. Sets defaults, creates WorkflowConfiguration, starts session, validates output directory, generates initial file instructions, and returns comprehensive workflow setup with next actions.
    async function buildCustomWorkflowImplementation(
      params: {
        task: string;
        workflowType?: WorkflowType | 'custom';
        selectedPhases?: Phase[];
        iterationLimits?: any;
        outputPreferences?: any;
        userCheckpoints?: any;
      },
      sessionManager: SessionManager
    ) {
      // Set defaults for optional parameters
      const selectedPhases = params.selectedPhases || ['SETUP', 'AUDIT_INVENTORY', 'WRITE_OR_REFACTOR', 'TEST', 'LINT', 'PRESENT'];
      const iterationLimits = {
        TEST: 5,
        LINT: 10,
        ITERATE: 15,
        ...params.iterationLimits
      };
      // Resolve output directory: if the incoming value is relative, make it absolute relative to working directory (CWD).
      const resolvedOutputDir = resolveOutputDirectory(
        params.outputPreferences?.outputDirectory || getDefaultOutputDirectory(),
        process.cwd()
      );
    
      const outputPreferences = {
        formats: ['markdown'],
        realTimeUpdates: true,
        generateDiagrams: true,
        includeCodeSnippets: true,
        createProgressReport: true,
        createPhaseArtifacts: true,
        ...params.outputPreferences,
        outputDirectory: resolvedOutputDir
      };
      const userCheckpoints = {
        beforeMajorChanges: true,
        afterFailedIterations: true,
        beforeFinalPresentation: false,
        ...params.userCheckpoints
      };
    
      // Create workflow configuration
      const workflowConfig: WorkflowConfiguration = {
        selectedPhases: selectedPhases as Phase[],
        iterationLimits,
        outputPreferences,
        userCheckpoints,
        escalationTriggers: {
          enableUserInput: true,
          escalateOnIterationLimit: true,
          escalateOnErrors: true,
          escalateOnTime: false
        }
      };
      // Start session with configuration
      const session = sessionManager.startSession(params.task, workflowConfig);
    
      // Validate directory access (read-only check)
      const dirValidation = validateDirectoryAccess(resolvedOutputDir);
      
      // Get the sanitized task name for subdirectory
      const sanitizedTaskName = sanitizeTaskName(params.task);
      
      // Construct the target directory path (no actual creation happens)
      const suggestedDirectory = resolvedOutputDir && sanitizedTaskName ? 
        `${resolvedOutputDir}/${sanitizedTaskName}` :
        resolvedOutputDir;
        
      // Report validation issues but continue with the workflow
      const directoryWarning = !dirValidation.isValid ? {
        warning: 'DIRECTORY ACCESS ISSUE',
        message: `âš ī¸ Output directory may not be writable: ${dirValidation.error}`,
        impact: 'The AI agent will be instructed to create this directory. If it fails, artifacts will remain in-memory only.',
        resolution: [
          'Check directory permissions',
          'Ensure the specified directory is writable'
        ]
      } : null;
    
      // Generate numbered file names for initial files
      const planningFileName = generateNumberedFileName({
        phase: 'PLANNING',
        outputDirectory: suggestedDirectory,
        extension: 'md',
        includeDate: true
      });
    
      // Generate initial output file instructions with numbered naming
      const initialOutputFiles: OutputFileInstruction[] = [
        {
          path: `${suggestedDirectory}/${planningFileName}`,
          description: 'Initial workflow plan and configuration',
          required: true,
          format: 'markdown',
          template: generateWorkflowPlanTemplate(params.task, workflowConfig),
          validationRules: ['Must contain task description', 'Must list all selected phases', 'Must include iteration limits']
        },
        {
          path: `${suggestedDirectory}/workflow-status.json`,
          description: 'Machine-readable workflow progress',
          required: true,
          format: 'json',
          template: JSON.stringify(sessionManager.getWorkflowProgress(), null, 2)
        }
      ];
    
      return {
        success: true,
        sessionId: session.id,
        message: '🚀 CUSTOM WORKFLOW BUILT SUCCESSFULLY',
        workflowConfiguration: {
          task: params.task,
          selectedPhases,
          phaseCount: selectedPhases.length,
          iterationLimits,
          outputPreferences,
          userCheckpoints,
          escalationEnabled: true
        },
        ...(directoryWarning ? { directoryWarning } : {}),
        criticalInstructions: [
          'âš ī¸ DIRECTIVE WORKFLOW: This is not suggestive guidance - you MUST follow the structured approach',
          '📋 PHASE VALIDATION: Each phase has specific completion requirements that must be met',
          '📁 OUTPUT REQUIREMENTS: You are required to create documentation files as specified',
          '🛑 SAFETY RULE: Files must be read before modification (this is enforced)',
          'âąī¸ ITERATION LIMITS: Automatic escalation to user input when limits are reached'
        ],
        directoryCreated: {
          baseDirectory: outputPreferences.outputDirectory,
          taskDirectory: suggestedDirectory,
          sanitizedTaskName: sanitizedTaskName,
          message: `â„šī¸ Suggested output directory path: ${suggestedDirectory}`
        },
        requiredFirstActions: [
          {
            action: 'CREATE_OUTPUT_DIRECTORY',
            instruction: `â„šī¸ Create output directory if needed: "${suggestedDirectory}"`,
            completed: false,
            blocking: true
          },
          {
            action: 'CREATE_INITIAL_FILES',
            instruction: 'You can now start creating phase output files using the numbered naming system',
            files: initialOutputFiles,
            blocking: false,
            note: 'Files will be automatically saved with numbered naming (01-audit-inventory-YYYY-MM-DD.md)'
          },
          {
            action: 'BEGIN_FIRST_PHASE',
            instruction: `Call "${selectedPhases[0].toLowerCase()}_guidance" to begin the workflow`,
            blocking: true
          }
        ],
        nextPhase: {
          phase: selectedPhases[0],
          tool: `${selectedPhases[0].toLowerCase()}_guidance`,
          description: `Begin with the ${selectedPhases[0]} phase`
        },
        validationRequirement: {
          message: '🔍 COMPLETION VALIDATION: You cannot proceed to the next phase until the current phase validation passes',
          enforcement: 'Use phase_output tool only after meeting all phase requirements'
        }
      };
  • createBuildCustomWorkflowTool: Defines the Tool object including name, description, and detailed inputSchema for parameter validation (task, workflowType, phases, limits, preferences).
    export function createBuildCustomWorkflowTool(): Tool {
      return {
        name: 'build_custom_workflow',
        description: 'Build a custom workflow with full control over phases and configuration. Use specific workflow tools (refactor_workflow, create_feature_workflow, etc.) for optimized presets.',
        inputSchema: {
          type: 'object',
          properties: {
            task: {
              type: 'string',
              description: 'Description of the programming task'
            },
            workflowType: {
              type: 'string',
              enum: ['refactor', 'feature', 'test', 'tdd', 'custom'],
              description: 'Use a predefined workflow type or custom for full control',
              default: 'custom'
            },
            selectedPhases: {
              type: 'array',
              items: {
                type: 'string',
                enum: ['SETUP', 'AUDIT_INVENTORY', 'COMPARE_ANALYZE', 'QUESTION_DETERMINE', 'WRITE_OR_REFACTOR', 'TEST', 'LINT', 'ITERATE', 'PRESENT']
              },
              description: 'Select which phases to include in your workflow',
              default: ['SETUP', 'AUDIT_INVENTORY', 'WRITE_OR_REFACTOR', 'TEST', 'LINT', 'PRESENT']
            },
            iterationLimits: {
              type: 'object',
              properties: {
                TEST: { type: 'number', default: 5, description: 'Max test failure cycles before user input' },
                LINT: { type: 'number', default: 10, description: 'Max lint/fix cycles before user input' },
                ITERATE: { type: 'number', default: 15, description: 'Max overall iterations before user input' }
              },
              description: 'Set iteration limits before escalation to user input'
            },
            outputPreferences: {
              type: 'object',
              properties: {
                formats: {
                  type: 'array',
                  items: { type: 'string', enum: ['markdown', 'json'] },
                  default: ['markdown'],
                  description: 'Output formats for documentation'
                },
                realTimeUpdates: { type: 'boolean', default: true },
                generateDiagrams: { type: 'boolean', default: true },
                includeCodeSnippets: { type: 'boolean', default: true },
                outputDirectory: { type: 'string', default: 'workflow-output' }
              }
            },
            userCheckpoints: {
              type: 'object',
              properties: {
                beforeMajorChanges: { type: 'boolean', default: true },
                afterFailedIterations: { type: 'boolean', default: true },
                beforeFinalPresentation: { type: 'boolean', default: false }
              }
            }
          },
          required: ['task']
        }
      };
    }
  • src/index.ts:137-158 (registration)
    Tool list registration: Adds createBuildCustomWorkflowTool() to the array of available tools served by the MCP server.
    const tools = [
      // Workflow entry points
      createRefactorWorkflowTool(),                 // Refactoring workflow
      createFeatureWorkflowTool(),                  // Feature creation workflow
      createTestWorkflowTool(),                     // Test writing workflow
      createTddWorkflowTool(),                      // TDD workflow
      createBuildCustomWorkflowTool(),              // Custom workflow builder
      
      // Phase guidance tools
      ...createPhaseGuidanceTools(),                // Handles both suggestive and directive modes
      createTestGuidanceTool(),                     // TEST phase guidance
      
      // Validation tools
      ...createValidationTools(),                   // Both validate_action and validate_phase_completion
      
      // Workflow management
      createUserInputRequiredTool(),                // Escalation handling
      createWorkflowStatusTool(),                   // Workflow status
      createPhaseOutputTool(),                      // Phase output recording
      createDiscoverWorkflowToolsTool()             // Tool discovery
    ];
  • src/index.ts:177-183 (registration)
    Handler dispatch registration: Switch case in CallToolRequestSchema handler that invokes handleBuildCustomWorkflow for 'build_custom_workflow' tool calls.
    case 'build_custom_workflow':
      return {
        content: [{
          type: 'text',
          text: JSON.stringify(await handleBuildCustomWorkflow(args as any, sessionManager), null, 2)
        }]
      };
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 'full control over phases and configuration,' which implies customization capabilities, but fails to disclose critical behavioral traits such as whether this is a read-only or mutating operation, authentication needs, rate limits, or what the tool actually produces (e.g., a workflow definition or execution). For a complex tool with 6 parameters and no annotations, this is a significant gap.

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, consisting of only two sentences. The first sentence directly states the purpose, and the second provides usage guidance. There is no wasted text, and every sentence earns its place by adding value.

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 (6 parameters, nested objects, no output schema, and no annotations), the description is incomplete. It lacks details on what the tool outputs, how it behaves (e.g., creates, updates, or executes workflows), error handling, or dependencies. For a tool with this level of complexity and no structured support, the description should provide more context to be adequate.

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 67%, meaning the schema documents most parameters well. The description adds minimal value beyond the schema, only implying that parameters relate to 'phases and configuration.' It doesn't explain parameter interactions, default behaviors, or provide examples. Given the high schema coverage, the baseline is 3, as the description doesn't significantly enhance parameter understanding.

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: 'Build a custom workflow with full control over phases and configuration.' It specifies the verb ('Build') and resource ('custom workflow'), and distinguishes it from sibling tools by mentioning 'specific workflow tools (refactor_workflow, create_feature_workflow, etc.) for optimized presets.' However, it doesn't explicitly differentiate this tool's unique scope beyond 'full control,' which keeps it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear usage guidance: 'Use specific workflow tools (refactor_workflow, create_feature_workflow, etc.) for optimized presets.' This indicates when to use this tool (for full control) versus alternatives (for presets). However, it doesn't explicitly state when not to use this tool or detail prerequisites, preventing a score of 5.

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/kingdomseed/structured-workflow-mcp'

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