Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@GYberkeley
Copy link

@GYberkeley GYberkeley commented Apr 14, 2025

User description

Primary Motivations: I mainly work in Arrangement View when I make a song so I wanted to add two convenience methods to the MCP. I also think that if you're creating a Session Clip its easier for the user to see what's happening if you switch to the Session View since most people start in Arrangement View by default.

Switch between Session and Arrangement View Demonstration:

switch_to_view
video link: https://drive.google.com/file/d/1Qr8NponBHczc7exToRxN30X9mc8_4KrM/view?usp=drive_link

Record a Session Clip into Arrangement View Demonstration:

record_into_arrangement

video link: https://drive.google.com/file/d/1qIOPs7p4QXiCVZpaZ6RegrE3avzKqAdC/view?usp=drive_link

This way you can

  1. Use Claude to Create a Session Clip with MIDI
  2. Record it straight into the Arrangement View

This allows Claude to potentially chain the two actions together (create a musical idea in Session View and then automatically recording it into Arrangement Mode)


PR Type

Enhancement


Description

  • Added functionality to switch between Session and Arrangement views.

  • Implemented recording of Session Clips into Arrangement View.

  • Enhanced command handling with new commands: record_arrangement_clip and switch_to_view.

  • Updated server-side tools to support new view-switching and recording features.


Changes walkthrough 📝

Relevant files
Enhancement
__init__.py
Introduced commands for view switching and clip recording

AbletonMCP_Remote_Script/init.py

  • Added record_arrangement_clip and switch_to_view commands.
  • Implemented _record_clip_to_arrangement for recording clips into
    Arrangement View.
  • Added _switch_to_view for toggling between Session and Arrangement
    views.
  • Enhanced error handling for new functionalities.
  • +72/-2   
    server.py
    Added tools for view switching and clip recording               

    MCP_Server/server.py

  • Added switch_to_view tool for toggling views.
  • Added record_arrangement_clip tool for recording Session Clips.
  • Updated create_clip to switch to Session View after creation.
  • Enhanced logging and error handling for new tools.
  • +67/-1   

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Summary by CodeRabbit

    • New Features
      • Introduced a command that lets you record clips directly in the arrangement view for streamlined clip management.
      • Added a command to switch seamlessly between Session and Arranger views, enhancing navigation and workflow.

    Add switch to view and add to arrangement view
    @coderabbitai
    Copy link

    coderabbitai bot commented Apr 14, 2025

    Walkthrough

    The changes add two new command types—record_arrangement_clip and switch_to_view—to both the Ableton remote script and the MCP server. In the remote script, new private methods (_get_clip_slot_by_name, _record_clip_to_arrangement, and _switch_to_view) have been introduced to handle clip recording and view switching. Similarly, the MCP server now features functions that validate and send these commands, including a modification to the clip creation logic for view adjustment.

    Changes

    File Change Summary
    AbletonMCP_Remote_Script/init.py Added new command handling in _process_command for record_arrangement_clip and switch_to_view. Introduced helper methods: _get_clip_slot_by_name, _record_clip_to_arrangement, and _switch_to_view to manage clip recording and view transitions.
    MCP_Server/server.py Introduced new functions record_arrangement_clip and switch_to_view to enable sending commands to Ableton. Updated the send_command method to include these new commands and modified create_clip to adjust the view post-creation.

    Sequence Diagram(s)

    sequenceDiagram
        participant U as User
        participant S as Server
        participant R as Remote Script
        participant A as Ableton Live
    
        U->>S: Call record_arrangement_clip(track_index, start_time, length, clip_index, clip_name)
        S->>A: send "record_arrangement_clip" command
        A->>R: Process command in _process_command
        R->>R: Execute _get_clip_slot_by_name & _record_clip_to_arrangement
        R->>A: Arm track & record clip in Arrangement view
        A-->>R: Return recording confirmation
        R-->>S: Acknowledge successful command execution
        S-->>U: Return success response
    
    Loading
    sequenceDiagram
        participant U as User
        participant S as Server
        participant R as Remote Script
        participant A as Ableton Live
    
        U->>S: Call switch_to_view(view_name)
        S->>A: send "switch_to_view" command
        A->>R: Process command in _process_command
        R->>R: Execute _switch_to_view to change view (Session/Arranger)
        R->>A: Update Ableton view state
        A-->>R: Confirm view switch
        R-->>S: Acknowledge successful command execution
        S-->>U: Return success response
    
    Loading

    Poem

    Oh, how the code takes a joyful leap,
    Commands now hop where MIDI clips sleep.
    Switching views with a skip and a bound,
    Recording magic in every sound.
    A rabbit sings through digital delight,
    Celebrating changes with pure code might!
    🐇🎶 Hop on!

    Tip

    ⚡💬 Agentic Chat (Pro Plan, General Availability)
    • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
    ✨ Finishing Touches
    • 📝 Generate Docstrings

    Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

    ❤️ Share
    🪧 Tips

    Chat

    There are 3 ways to chat with CodeRabbit:

    • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
      • I pushed a fix in commit <commit_id>, please review it.
      • Generate unit testing code for this file.
      • Open a follow-up GitHub issue for this discussion.
    • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
      • @coderabbitai generate unit testing code for this file.
      • @coderabbitai modularize this function.
    • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
      • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
      • @coderabbitai read src/utils.ts and generate unit testing code.
      • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
      • @coderabbitai help me debug CodeRabbit configuration file.

    Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

    CodeRabbit Commands (Invoked using PR comments)

    • @coderabbitai pause to pause the reviews on a PR.
    • @coderabbitai resume to resume the paused reviews.
    • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
    • @coderabbitai full review to do a full review from scratch and review all the files again.
    • @coderabbitai summary to regenerate the summary of the PR.
    • @coderabbitai generate docstrings to generate docstrings for this PR.
    • @coderabbitai resolve resolve all the CodeRabbit review comments.
    • @coderabbitai plan to trigger planning for file edits and PR creation.
    • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
    • @coderabbitai help to get help.

    Other keywords and placeholders

    • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
    • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
    • Add @coderabbitai anywhere in the PR title to generate the title automatically.

    CodeRabbit Configuration File (.coderabbit.yaml)

    • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
    • Please see the configuration documentation for more information.
    • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

    Documentation and Community

    • Visit our Documentation for detailed information on how to use CodeRabbit.
    • Join our Discord Community to get help, request features, and share feedback.
    • Follow us on X/Twitter for updates and announcements.

    @qodo-code-review
    Copy link

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Timing Issue

    The _record_clip_to_arrangement method uses time.sleep() which blocks the main thread. This could cause UI freezing and timing issues since sleep is not synchronized with Ableton's timing system.

    time.sleep(length * 60.0 / self._song.tempo)
    Error Handling

    The _record_clip_to_arrangement method doesn't restore state if an exception occurs. If an error happens during recording, the song might be left in recording mode.

    def _record_clip_to_arrangement(self, track_index, start_time, length, clip_index, clip_name):
        """Record a new Arrangement MIDI clip in the Arrangement View at the specified time."""
        try:
            track = self.song().tracks[track_index]
            if track.can_be_armed and not track.arm:
                track.arm = True
    
            clip_slot = None
    
            if clip_name:
                clip_slot = self._get_clip_slot_by_name(track, clip_name)
            else:
                clip_slot = track.clip_slots[clip_index]
    
            clip_slot.fire()
            # Start Recording the Session Clip into Arrangement View
            self._song.record_mode = True
            self._song.start_playing()
            self._song.is_playing = True
            self._song.start_time = start_time
    
            time.sleep(length * 60.0 / self._song.tempo)
    
            self._song.is_playing = False
            self._song.stop_playing()
            self._song.record_mode = False
            clip_slot.stop()
    
            result = {
                "created_arrangement_clip": True
            }
            return result
        except Exception as e:
            self.log_message("Error creating arrangement clip: " + str(e))
            raise
    String Interpolation

    The return message in record_arrangement_clip uses $ for string interpolation which is incorrect in Python. It should use an f-string format.

        return f"Created arrangement clip from Track ${track_index}"
    except Exception as e:

    @qodo-code-review
    Copy link

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Avoid blocking with sleep

    The use of time.sleep() in the main thread will block the entire application,
    causing the UI to freeze during recording. Instead, use a non-blocking approach
    with a timer or callback function to stop recording after the specified
    duration.

    AbletonMCP_Remote_Script/init.py [501-535]

     def _record_clip_to_arrangement(self, track_index, start_time, length, clip_index, clip_name):
         """Record a new Arrangement MIDI clip in the Arrangement View at the specified time."""
         try:
             track = self.song().tracks[track_index]
             if track.can_be_armed and not track.arm:
                 track.arm = True
                 
             clip_slot = None
             
             if clip_name:
                 clip_slot = self._get_clip_slot_by_name(track, clip_name)
             else:
                 clip_slot = track.clip_slots[clip_index]
             
             clip_slot.fire()
             # Start Recording the Session Clip into Arrangement View
             self._song.record_mode = True
             self._song.start_playing()
             self._song.is_playing = True
             self._song.start_time = start_time
     
    -        time.sleep(length * 60.0 / self._song.tempo)
    +        # Schedule stopping the recording after the specified duration
    +        self.schedule_message(int(length * 60.0 / self._song.tempo * 1000), self._stop_recording_arrangement_clip, clip_slot)
     
    -        self._song.is_playing = False
    -        self._song.stop_playing()
    -        self._song.record_mode = False
    -        clip_slot.stop()
    +        result = {
    +            "created_arrangement_clip": True
    +        }
    +        return result
    +    except Exception as e:
    +        self.log_message("Error creating arrangement clip: " + str(e))
    +        raise
    +        
    +def _stop_recording_arrangement_clip(self, clip_slot):
    +    """Stop recording and playback after scheduled time"""
    +    self._song.is_playing = False
    +    self._song.stop_playing()
    +    self._song.record_mode = False
    +    clip_slot.stop()

    [To ensure code accuracy, apply this suggestion manually]

    Suggestion importance[1-10]: 9

    __

    Why: Using time.sleep() in the main thread is a critical issue that would freeze the entire Ableton Live UI during recording. The suggested non-blocking approach with schedule_message() is the correct pattern for Live scripts and would prevent UI freezing while maintaining functionality.

    High
    Validate clip slot existence

    There's no validation to check if clip_slot is actually found or if it contains
    a clip. If clip_name is provided but not found, or if clip_index is out of
    range, clip_slot could be None or reference an empty clip slot, causing a
    runtime error when fire() is called.

    AbletonMCP_Remote_Script/init.py [510-515]

     if clip_name:
         clip_slot = self._get_clip_slot_by_name(track, clip_name)
     else:
    -    clip_slot = track.clip_slots[clip_index]
    +    if 0 <= clip_index < len(track.clip_slots):
    +        clip_slot = track.clip_slots[clip_index]
    +    else:
    +        raise ValueError(f"Invalid clip_index: {clip_index}")
    +
    +if clip_slot is None or not clip_slot.has_clip:
    +    raise ValueError(f"No clip found with name '{clip_name}' or at index {clip_index}")
     
     clip_slot.fire()
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    __

    Why: This suggestion addresses a potential runtime error that could occur if the clip_slot is None or doesn't contain a clip. Adding proper validation prevents crashes when invalid clip names or indices are provided, which is important for robust error handling.

    Medium
    Fix string interpolation syntax

    The string interpolation uses JavaScript-style ${} syntax instead of Python's
    f-string format. This will output the literal $track_index instead of the actual
    track index value.

    MCP_Server/server.py [716]

    -return f"Created arrangement clip from Track ${track_index}"
    +return f"Created arrangement clip from Track {track_index}"
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    __

    Why: The code uses JavaScript-style string interpolation ($) instead of Python's format, which would display the literal "$track_index" rather than the variable value. This is a straightforward but important fix for correct user feedback.

    Medium
    • More

    Copy link

    @coderabbitai coderabbitai bot left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Actionable comments posted: 2

    🧹 Nitpick comments (1)
    AbletonMCP_Remote_Script/__init__.py (1)

    501-536: Consider a more asynchronous approach for waiting during recording.

    The current implementation uses time.sleep() to wait for the recording to complete, which blocks the thread and could potentially cause the UI to freeze or prevent other commands from being processed during this time.

    Consider implementing a more asynchronous approach or at least documenting this blocking behavior. For example, you could set up a timer callback instead of using sleep:

    def _record_clip_to_arrangement(self, track_index, start_time, length, clip_index, clip_name):
        """Record a new Arrangement MIDI clip in the Arrangement View at the specified time."""
        try:
            track = self.song().tracks[track_index]
            if track.can_be_armed and not track.arm:
                track.arm = True
                
            clip_slot = None
            
            if clip_name:
                clip_slot = self._get_clip_slot_by_name(track, clip_name)
            else:
                clip_slot = track.clip_slots[clip_index]
            
            clip_slot.fire()
            # Start Recording the Session Clip into Arrangement View
            self._song.record_mode = True
            self._song.start_playing()
            self._song.is_playing = True
            self._song.start_time = start_time
    
            # Calculate the duration in milliseconds
            duration_ms = int(length * 60.0 / self._song.tempo * 1000)
            
            # Use schedule_message instead of sleep
            def stop_recording():
                self._song.is_playing = False
                self._song.stop_playing()
                self._song.record_mode = False
                clip_slot.stop()
            
            self.schedule_message(duration_ms, stop_recording)
    
            result = {
                "created_arrangement_clip": True
            }
            return result
        except Exception as e:
            self.log_message("Error creating arrangement clip: " + str(e))
            raise
    📜 Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL
    Plan: Pro

    📥 Commits

    Reviewing files that changed from the base of the PR and between bea865e and 033119a.

    📒 Files selected for processing (2)
    • AbletonMCP_Remote_Script/__init__.py (4 hunks)
    • MCP_Server/server.py (3 hunks)
    🧰 Additional context used
    🪛 Ruff (0.8.2)
    MCP_Server/server.py

    673-673: f-string without any placeholders

    Remove extraneous f prefix

    (F541)


    705-705: Local variable result is assigned to but never used

    Remove assignment to unused variable result

    (F841)

    🔇 Additional comments (6)
    MCP_Server/server.py (2)

    108-109: Good addition to the state-modifying commands list.

    The new command types "record_arrangement_clip" and "switch_to_view" have been properly added to the list of state-modifying commands, which ensures appropriate timeouts and delays will be applied during communication with Ableton.


    340-341: Good addition to ensure consistent view state.

    Adding the view switching after clip creation ensures users always end up in Session View after creating a clip, providing a consistent experience aligned with the PR objectives.

    AbletonMCP_Remote_Script/__init__.py (4)

    233-233: Good addition to the command processing list.

    The new command types "record_arrangement_clip" and "switch_to_view" have been properly added to the list of commands processed on the main thread, which is important for thread safety.


    286-295: Good implementation of the new command handler.

    The code correctly extracts all necessary parameters and calls the appropriate method to handle the record arrangement clip functionality.


    495-499: Well-designed helper method.

    The _get_clip_slot_by_name method provides a clean way to find a clip slot by name, which is a useful utility for the record arrangement clip functionality.


    537-552: Good implementation for view switching.

    The _switch_to_view method properly handles switching between Session and Arrangement views, focusing the appropriate view and updating the song's back_to_arranger property.

    Comment on lines +658 to +683
    @mcp.tool()
    def switch_to_view(ctx: Context, view_name: str = "Arranger") -> str:
    """
    Switch between Arrangement (called Arranger) and Session View
    Parameters:
    - view_name: Either "Arranger" or "Session"
    """
    try:

    ableton = get_ableton_connection()

    # Validate view name
    view_name = view_name.capitalize()
    if view_name not in ["Arranger", "Session"]:
    return f"Invalid view name. Must be either 'Arrangement' or 'Session'"

    result = ableton.send_command("switch_to_view", {
    "view_name": view_name
    })

    return f"Switched to {view_name} view. Result: {result}"
    except Exception as e:
    logger.error(f"Error switching view: {str(e)}")
    return f"Error switching view: {str(e)}"

    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    🛠️ Refactor suggestion

    Fix the f-string and error message consistency.

    There are two issues in this implementation:

    1. Line 673 uses an f-string without any variables
    2. The error message mentions "Arrangement" but the code checks for "Arranger" which could confuse users
    -        if view_name not in ["Arranger", "Session"]:
    -            return f"Invalid view name. Must be either 'Arrangement' or 'Session'"
    +        if view_name not in ["Arranger", "Session"]:
    +            return "Invalid view name. Must be either 'Arranger' or 'Session'"
    📝 Committable suggestion

    ‼️ IMPORTANT
    Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    Suggested change
    @mcp.tool()
    def switch_to_view(ctx: Context, view_name: str = "Arranger") -> str:
    """
    Switch between Arrangement (called Arranger) and Session View
    Parameters:
    - view_name: Either "Arranger" or "Session"
    """
    try:
    ableton = get_ableton_connection()
    # Validate view name
    view_name = view_name.capitalize()
    if view_name not in ["Arranger", "Session"]:
    return f"Invalid view name. Must be either 'Arrangement' or 'Session'"
    result = ableton.send_command("switch_to_view", {
    "view_name": view_name
    })
    return f"Switched to {view_name} view. Result: {result}"
    except Exception as e:
    logger.error(f"Error switching view: {str(e)}")
    return f"Error switching view: {str(e)}"
    @mcp.tool()
    def switch_to_view(ctx: Context, view_name: str = "Arranger") -> str:
    """
    Switch between Arrangement (called Arranger) and Session View
    Parameters:
    - view_name: Either "Arranger" or "Session"
    """
    try:
    ableton = get_ableton_connection()
    # Validate view name
    view_name = view_name.capitalize()
    if view_name not in ["Arranger", "Session"]:
    return "Invalid view name. Must be either 'Arranger' or 'Session'"
    result = ableton.send_command("switch_to_view", {
    "view_name": view_name
    })
    return f"Switched to {view_name} view. Result: {result}"
    except Exception as e:
    logger.error(f"Error switching view: {str(e)}")
    return f"Error switching view: {str(e)}"
    🧰 Tools
    🪛 Ruff (0.8.2)

    673-673: f-string without any placeholders

    Remove extraneous f prefix

    (F541)

    Comment on lines +684 to +720
    @mcp.tool()
    def record_arrangement_clip(
    ctx: Context,
    track_index: int,
    start_time: float = 0.0,
    length: float = 4.0,
    clip_index: int = -1,
    clip_name: str = ""
    ) -> str:
    """
    Record into the Arrangement View from the Session View
    Parameters:
    - track_index: Which track to create the clip on
    - start_time: Start time in beats
    - length: Length of the clip in beats
    """
    try:
    ableton = get_ableton_connection()

    # Create the clip in arrangement view
    result = ableton.send_command("record_arrangement_clip", {
    "track_index": track_index,
    "start_time": start_time,
    "length": length,
    "clip_index": clip_index,
    "clip_name": clip_name
    })

    # Switch to Arrangement View
    ableton.send_command("switch_to_view", {"view_name": "Arranger"})

    return f"Created arrangement clip from Track ${track_index}"
    except Exception as e:
    logger.error(f"Error creating arrangement clip: {str(e)}")
    return f"Error creating arrangement clip: {str(e)}"

    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    🛠️ Refactor suggestion

    Fix string interpolation and unused variable.

    There are two issues in this function:

    1. The result variable on line 705 is assigned but never used, which could indicate a missing check or operation
    2. On line 716, the string interpolation uses $ syntax instead of Python's f-string {} syntax
    -        # Create the clip in arrangement view
    -        result = ableton.send_command("record_arrangement_clip", {
    +        # Create the clip in arrangement view and check result
    +        arrangement_result = ableton.send_command("record_arrangement_clip", {
                 "track_index": track_index,
                 "start_time": start_time,
                 "length": length,
                 "clip_index": clip_index,
                 "clip_name": clip_name
             })
             
             # Switch to Arrangement View
             ableton.send_command("switch_to_view", {"view_name": "Arranger"})
             
    -        return f"Created arrangement clip from Track ${track_index}"
    +        return f"Created arrangement clip from Track {track_index}"

    Committable suggestion skipped: line range outside the PR's diff.

    🧰 Tools
    🪛 Ruff (0.8.2)

    705-705: Local variable result is assigned to but never used

    Remove assignment to unused variable result

    (F841)

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    1 participant