Skip to main content
Glama

playTrack

Search for a track on YouTube Music and open the top result in your browser. Use this tool to quickly find and play music tracks through natural language commands.

Instructions

Search for a track on YouTube Music and open the top result in the default browser.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
trackNameYesThe name of the track to search for and play

Implementation Reference

  • The core handler logic for the 'playTrack' tool. It searches for the track on YouTube using the API, extracts the top video ID, constructs the YouTube Music watch URL, opens it in the default browser, and returns a success message or handles errors.
    async ({ trackName }) => {
      try {
        const searchResults = await searchYoutubeVideo(apiKey, trackName, 1)
    
        if (searchResults.length === 0) {
          return {
            content: [{ type: 'text', text: `No search results found for: ${trackName}` }],
          }
        }
    
        const topResult = searchResults[0]
        const videoId = topResult?.id?.videoId
        const title = topResult?.snippet?.title ?? 'Unknown Title'
    
        if (!videoId) {
          console.error('Could not find video ID in top search result:', topResult)
          throw new McpError(ErrorCode.InternalError, 'Could not extract video ID from YouTube search result.')
        }
    
        const youtubeMusicUrl = `${YOUTUBE_MUSIC_WATCH_URL_PREFIX}${videoId}`
    
        await openUrlInBrowser(youtubeMusicUrl)
    
        return {
          content: [{ type: 'text', text: `Attempting to play in browser: ${title} (${youtubeMusicUrl})` }],
        }
      }
      catch (error: unknown) {
        console.error('Error in playTrack tool:', error)
        if (error instanceof McpError && error.code === ErrorCode.InternalError) {
          throw error
        }
        const message = error instanceof McpError
          ? error.message
          : error instanceof Error
            ? error.message
            : 'An unexpected error occurred during track playback.'
    
        return {
          content: [{ type: 'text', text: `Error playing track: ${message}` }],
          isError: true,
        }
      }
    },
  • Zod input schema for the 'playTrack' tool defining the required 'trackName' parameter.
    {
      trackName: z.string().describe('The name of the track to search for and play'),
    },
  • src/index.ts:15-15 (registration)
    Top-level call to register the YouTube Music tools, including 'playTrack', in the MCP server.
    registerToolYoutubeMusic({ mcp } as McpToolContext)
  • Platform-specific helper to open a URL in the default browser (Chrome on macOS, system default otherwise). Called by playTrack handler to play the track.
    async function openUrlInBrowser(url: string, platform: NodeJS.Platform = process.platform): Promise<void> {
      let command: string = ''
    
      try {
        if (platform === 'darwin') {
          const appleScript = `tell application "Google Chrome" to open location "${url}"`
          command = `osascript -e '${appleScript.replace(/'/g, "'\''")}'`
          console.log(`Executing command for macOS: ${command}`)
          const { stderr } = await execPromise(command)
          if (stderr) {
            console.warn('osascript stderr:', stderr)
          }
        }
        else if (platform === 'win32') {
          command = `start "" "${url}"`
          console.log(`Executing command for Windows: ${command}`)
          await execPromise(command)
        }
        else {
          // Assume Linux/other POSIX-like
          command = `xdg-open "${url}"`
          console.log(`Executing command for Linux/Other: ${command}`)
          await execPromise(command)
        }
      }
      catch (execError: unknown) {
        console.error(`Error executing command "${command}":`, execError)
        const errorMsg = execError instanceof Error ? execError.message : 'Unknown execution error'
        throw new McpError(ErrorCode.InternalError, `Failed to open URL in browser: ${errorMsg}`)
      }
    }
  • YouTube API search helper function to find video results by query. Used by playTrack to locate the track.
    async function searchYoutubeVideo(
      apiKey: string,
      query: string,
      maxResults: number = 5,
    ): Promise<YouTubeSearchResultItem[]> {
      try {
        const searchResults = await ofetch<YouTubeSearchResults>('/search', {
          baseURL: YOUTUBE_API_BASE_URL,
          query: {
            key: apiKey,
            part: 'snippet',
            maxResults,
            type: 'video',
            q: query,
          },
        })
        return searchResults?.items ?? []
      }
      catch (error: unknown) {
        console.error('Error fetching YouTube search results:', error)
        const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred during YouTube search'
        throw new McpError(ErrorCode.InternalError, `YouTube API search failed: ${errorMessage}`)
      }
    }
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses that the tool opens the top result in the default browser, which is useful behavioral context, but does not mention potential side effects like browser pop-ups, authentication needs, or rate limits.

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 a single, efficient sentence that front-loads the core action without any wasted words, making it easy to understand quickly.

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?

Given the tool's moderate complexity (searching and opening in browser) with no annotations or output schema, the description is reasonably complete but lacks details on error handling, what happens if no results are found, or the format of any potential output.

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 100%, so the schema already documents the 'trackName' parameter. The description adds no additional meaning beyond implying the parameter is used for searching, which aligns with the schema's description.

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 specific action ('search for a track on YouTube Music and open the top result in the default browser') with the resource ('track'), distinguishing it from the sibling tool 'searchTrack' which presumably only searches without opening.

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 implies usage for playing tracks via YouTube Music, but does not explicitly state when to use this tool versus 'searchTrack' or other alternatives, nor does it provide exclusions or prerequisites.

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/instructa/mcp-youtube-music'

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