Skip to main content
Glama

generate_melody

Create a melody by specifying a scale and root note, with optional control over note count.

Instructions

Generate melody from scale

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scaleYesScale name
rootYesRoot note
lengthNoNumber of notes

Implementation Reference

  • Schema definition for the generate_melody tool: name, description, and inputSchema with scale (string, required), root (string, required), and length (number, optional).
    {
      name: 'generate_melody',
      description: 'Generate melody from scale',
      inputSchema: {
        type: 'object',
        properties: {
          scale: { type: 'string', description: 'Scale name' },
          root: { type: 'string', description: 'Root note' },
          length: { type: 'number', description: 'Number of notes' },
        },
        required: ['scale', 'root'],
      },
    },
  • Handler for generate_melody: validates root note, scale name, and optional length; builds the scale via ctx.theory.generateScale(); generates the melody via ctx.generator.generateMelody(scale, length); appends the result to the current pattern; returns a confirmation string.
    case 'generate_melody': {
      InputValidator.validateRootNote(args.root);
      InputValidator.validateScaleName(args.scale);
      if (args.length !== undefined) InputValidator.validatePositiveInteger(args.length, 'length');
      const scale = ctx.theory.generateScale(args.root, args.scale);
      const melody = ctx.generator.generateMelody(scale, args.length || 8);
      await appendOrSet(melody, ctx);
      return `Generated melody in ${args.root} ${args.scale}`;
    }
  • Core generateMelody() implementation on PatternGenerator class. Takes a scale array, length (default 8), and octaveRange (default [3,5]). Creates a note sequence that prefers stepwise motion (70% probability) over leaps, with random octave selection, outputting Strudel-compatible code: note('...').s('triangle').
    /**
     * Generates a melodic pattern from a scale
     * @param scale - Array of note names to use
     * @param length - Number of notes in the melody (default: 8)
     * @param octaveRange - Tuple of min and max octave numbers (default: [3, 5])
     * @returns Strudel melody pattern code
     */
    generateMelody(scale: string[], length: number = 8, octaveRange: [number, number] = [3, 5]): string {
      const notes = [];
      let lastNoteIndex = Math.floor(Math.random() * scale.length);
      
      for (let i = 0; i < length; i++) {
        // Create more musical intervals (prefer steps over leaps)
        const stepProbability = 0.7;
        const useStep = Math.random() < stepProbability;
        
        let noteIndex: number;
        if (useStep) {
          // Move by step (1 or 2 scale degrees)
          const step = Math.random() < 0.5 ? 1 : -1;
          noteIndex = (lastNoteIndex + step + scale.length) % scale.length;
        } else {
          // Leap to any note
          noteIndex = Math.floor(Math.random() * scale.length);
        }
        
        const note = scale[noteIndex];
        const octave = octaveRange[0] + Math.floor(Math.random() * (octaveRange[1] - octaveRange[0] + 1));
        notes.push(`${note.toLowerCase()}${octave}`);
        lastNoteIndex = noteIndex;
      }
      
      return `note("${notes.join(' ')}").s("triangle")`;
    }
  • Registration wiring in server.ts: generate_melody is listed among generation tools that require write access (line 220) and is handled specially to allow execution without browser initialization (line 298). The tool is exposed via ...generateModule.tools (line 114).
    private requiresInitialization(toolName: string): boolean {
      const toolsRequiringInit = [
        'write', 'append', 'insert', 'replace', 'play', 'pause', 'stop',
        'clear', 'get_pattern', 'analyze', 'analyze_spectrum', 'analyze_rhythm',
        'transpose', 'reverse', 'stretch', 'humanize', 'generate_variation',
        'add_effect', 'add_swing', 'set_tempo', 'save', 'undo', 'redo',
        'validate_pattern_runtime'
      ];
      
      const toolsRequiringWrite = [
        'generate_pattern', 'generate_drums', 'generate_bassline', 'generate_melody',
        'generate_chord_progression', 'generate_euclidean', 'generate_polyrhythm',
        'generate_fill'
      ];
      
      return toolsRequiringInit.includes(toolName) || toolsRequiringWrite.includes(toolName);
    }
  • Additional call site in ai.ts where generateMelody is invoked with 8 notes and style-specific effects appended (e.g., for AI-generated melodic parts).
      const scale = ctx.theory.generateScale(key, scaleName);
      const effects: Record<string, string> = {
        'techno': '.delay(0.25).room(0.2)', 'house': '.room(0.3).gain(0.6)',
        'dnb': '.delay(0.125).room(0.2).gain(0.5)', 'ambient': '.room(0.7).delay(0.5).gain(0.4)',
        'trap': '.gain(0.5).room(0.15)', 'jungle': '.delay(0.125).room(0.25).gain(0.55)',
        'jazz': '.room(0.4).gain(0.5)',
      };
      return ctx.generator.generateMelody(scale, 8, octaveRange) + (effects[style] || '.room(0.3).gain(0.5)');
    }
Behavior2/5

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

With no annotations, the description should disclose behaviors like determinism, state changes, or output format. It only says 'generate melody' with no additional behavioral context.

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 sentence with no waste, but it omits important details that could be added without loss of conciseness. Front-loaded but too terse.

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 3 parameters, no output schema, and many sibling tools, the description lacks context about return values, parameter constraints, or how this tool fits into a workflow. Inadequate for its complexity.

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?

Input schema has 100% coverage; descriptions like 'Scale name' suffice. The tool description adds no new meaning beyond the schema, so baseline 3 is appropriate.

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 verb (generate) and resource (melody) with a source (scale), but does not distinguish from sibling tools like generate_bassline or generate_drums. It is clear but lacks differentiation.

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?

No guidance is provided on when to use generate_melody versus alternatives, nor any prerequisites or constraints (e.g., scale format, root note conventions).

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/williamzujkowski/live-coding-music-mcp'

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