Skip to main content
Glama

Wait for Task Completion

task_barrier

Wait for all submitted tasks to complete and retrieve results in batch. Submit multiple tasks first, then use this to collect all outputs. Clears completed tasks.

Instructions

Wait for ALL submitted tasks to complete and retrieve results. Essential for batch processing - submit multiple tasks first, then call task_barrier once to collect all results efficiently. Clears completed tasks.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler logic for the task_barrier tool. It validates params (empty object), calls taskManager.barrier() to wait for all submitted tasks, formats results (success/failure for image and TTS tasks), then calls clearCompletedTasks() to prevent memory leaks.
    // Task barrier tool
    server.registerTool(
      "task_barrier",
      {
        title: "Wait for Task Completion",
        description: "Wait for ALL submitted tasks to complete and retrieve results. Essential for batch processing - submit multiple tasks first, then call task_barrier once to collect all results efficiently. Clears completed tasks.",
        inputSchema: taskBarrierSchema.shape
      },
      async (params: unknown): Promise<ToolResponse> => {
        try {
          validateTaskBarrierParams(params);
          const { completed, results } = await taskManager.barrier();
          
          if (completed === 0) {
            return {
              content: [{
                type: "text",
                text: "ℹ️ No tasks were submitted before this barrier."
              }]
            };
          }
    
          // Format results
          const resultSummaries = results.map(({ taskId, success, result, error }) => {
            if (!success) {
              return `❌ Task ${taskId}: FAILED - ${error?.message || 'Unknown error'}`;
            }
    
            // Format success results based on task type
            if (result?.files) {
              // Image generation result
              const warnings = result.warnings ? ` (${result.warnings.length} warnings)` : '';
              return `✅ Task ${taskId}: Generated ${result.count} image(s)${warnings}`;
            } else if (result?.audioFile) {
              // TTS generation result
              const subtitles = result.subtitleFile ? ` + subtitles` : '';
              const warnings = result.warnings ? ` (${result.warnings.length} warnings)` : '';
              return `✅ Task ${taskId}: Generated speech${subtitles}${warnings}`;
            } else {
              // Generic success
              return `✅ Task ${taskId}: Completed successfully`;
            }
          });
    
          const summary = resultSummaries.join('\n');
    
          // Clear completed tasks to prevent memory leaks
          taskManager.clearCompletedTasks();
    
          return {
            content: [{
              type: "text",
              text: summary
            }]
          };
        } catch (error: any) {
          ErrorHandler.logError(error, { tool: 'task_barrier' });
          return {
            content: [{
              type: "text",
              text: `❌ Task barrier failed: ${ErrorHandler.formatErrorForUser(error)}`
            }]
          };
        }
      }
    );
  • The barrier() method in TaskManager class. Waits for all active tasks via Promise.allSettled, then returns all completed tasks (taskId, success, result, error). This is the core blocking/waiting mechanism.
    async barrier(): Promise<BarrierResult> {
      const activeTasks = Array.from(this.tasks.values());
      
      // Wait for any active tasks to complete
      if (activeTasks.length > 0) {
        await Promise.allSettled(activeTasks);
      }
    
      // Return all completed tasks (including those completed before this barrier call)
      const results = Array.from(this.completedTasks.entries()).map(([taskId, taskResult]) => ({
        taskId,
        ...taskResult
      }));
    
      return { completed: results.length, results };
    }
  • src/index.ts:123-129 (registration)
    Registration of the task_barrier tool via server.registerTool with name 'task_barrier', title 'Wait for Task Completion', description explaining batch usage, and inputSchema from taskBarrierSchema.shape (empty object).
    server.registerTool(
      "task_barrier",
      {
        title: "Wait for Task Completion",
        description: "Wait for ALL submitted tasks to complete and retrieve results. Essential for batch processing - submit multiple tasks first, then call task_barrier once to collect all results efficiently. Clears completed tasks.",
        inputSchema: taskBarrierSchema.shape
      },
  • Zod schema definition for task_barrier - an empty object schema (no params needed). Also includes the TaskBarrierParams type inference and the JSON schema variant taskBarrierToolSchema (lines 305-308).
    // Task barrier schema
    export const taskBarrierSchema = z.object({});
    
    // Type definitions for parsed schemas
    export type ImageGenerationParams = z.infer<typeof imageGenerationSchema>;
    export type TextToSpeechParams = z.infer<typeof textToSpeechSchema>;
    export type TaskBarrierParams = z.infer<typeof taskBarrierSchema>;
  • Validation helper function validateTaskBarrierParams that parses input against the empty taskBarrierSchema, throwing friendly error messages on failure.
    export function validateTaskBarrierParams(params: unknown): TaskBarrierParams {
      try {
        return taskBarrierSchema.parse(params);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const messages = error.errors.map(e => `${e.path.join('.')}: ${e.message}`);
          throw new Error(`Validation failed: ${messages.join(', ')}`);
        }
        throw error;
      }
    }
Behavior3/5

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

With no annotations, the description includes a side effect (clears completed tasks) and implies blocking behavior. However, it lacks details on timeouts, error handling, or concurrency, which would be helpful.

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, with two sentences that efficiently convey purpose, usage, and a behavioral note. No wasted words.

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?

For a no-parameter, no-output-schema tool, the description covers purpose, usage, and side effects. It is complete enough given the simplicity, though more detail on behavior would elevate it.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

There are zero parameters, so baseline is 4. The description does not need to add parameter info, and it is consistent with the empty schema.

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 the tool waits for all submitted tasks to complete and retrieves results, using a specific verb-resource combination. It is well-differentiated from sibling submission tools.

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 explicitly advises using this after submitting multiple tasks for efficient batch processing, providing a clear usage context. It does not mention when not to use or alternatives, but the guidance is sufficient.

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/PsychArch/minimax-mcp-tools'

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