> ## Documentation Index
> Fetch the complete documentation index at: https://docs.atxp.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Music

> Create and edit music

## Overview

Use the Music MCP server from your ATXP-powered agent to create music from a natural-language prompt.

## Example prompts

* "Create a modern country song about a cat riding a horse."
* "Create an electronic dance music song about a child and a puppy."

## Tools

<AccordionGroup>
  <Accordion title="music_create">
    Take in lyrics and prompt and produce a hex encoded MP3 file. An example prompt would be "polka, upbeat, fast". Example lyrics would be "\[intro]Hey there cowboy\[verse]That's a mighty fine horse you got\[outro]". The output will contain a URL to the MP3 file.

    ### Arguments

    Accepts a JSON object with the following properties:

    <ParamField body="prompt" type="string" required>
      The prompt for the music. For example, what style of music to create. Example: "blues, melancholic, raw, lonely bar, heartbreak"
    </ParamField>

    <ParamField body="lyrics" type="string" default="[instrumental]">
      The lyrics you would like to include in the music. You can use new lines to separate verses. You can use \[intro]\[verse]\[chorus]\[bridge]\[outro] to specify the structure of the song. Defaults to "\[instrumental]" for instrumental music.
    </ParamField>

    ### Response

    Returns a JSON object with the following properties:

    <ResponseField name="status" type="string">
      The status of the music generation operation. Returns "success" when the music is generated successfully.
    </ResponseField>

    <ResponseField name="url" type="string">
      The URL that the generated MP3 file is accessible at.
    </ResponseField>
  </Accordion>

  <Accordion title="music_create_async">
    Takes in lyrics and prompt and starts asynchronous music generation. Returns a task ID that can be used to check status and retrieve the result. Use this for longer music generation tasks to avoid timeouts.

    ### Arguments

    Accepts a JSON object with the following properties:

    <ParamField body="prompt" type="string" required>
      The prompt for the music. For example, what style of music to create. Example: "blues, melancholic, raw, lonely bar, heartbreak"
    </ParamField>

    <ParamField body="lyrics" type="string" default="[instrumental]">
      The lyrics you would like to include in the music. You can use new lines to separate verses. You can use \[intro]\[verse]\[chorus]\[bridge]\[outro] to specify the structure of the song. Defaults to "\[instrumental]" for instrumental music.
    </ParamField>

    ### Response

    Returns a JSON object with the following properties:

    <ResponseField name="taskId" type="string">
      A unique task identifier that can be used with `music_get_async` to check the status and retrieve the result.
    </ResponseField>
  </Accordion>

  <Accordion title="music_get_async">
    Retrieves the status and result of an asynchronous music generation task using the task ID. Tasks expire after 12 hours.

    ### Arguments

    Accepts a JSON object with the following properties:

    <ParamField body="taskId" type="string" required>
      The task ID returned from `music_create_async`.
    </ParamField>

    ### Response

    Returns a JSON object with the following properties:

    <ResponseField name="status" type="string">
      The current status of the task. Can be "pending", "running", "completed", or "error".
    </ResponseField>

    <ResponseField name="url" type="string">
      The URL that the generated MP3 file is accessible at. Only present when status is "completed".
    </ResponseField>

    <ResponseField name="createdAt" type="number">
      Timestamp when the task was created.
    </ResponseField>

    <ResponseField name="completedAt" type="number">
      Timestamp when the task was completed. Only present when status is "completed" or "error".
    </ResponseField>

    <ResponseField name="errorMessage" type="string">
      Error message if the task failed. Only present when status is "error".
    </ResponseField>
  </Accordion>
</AccordionGroup>

## Usage

<Steps>
  <Step title="Define the Music service">
    Create a reusable service configuration that points to the MCP server and standardizes how you pass arguments and read results. This lets your agent easily interact with the Music tools in a consistent manner.

    ```typescript theme={null}
    const musicService = {
        mcpServer: 'https://music.mcp.atxp.ai/',
        createMusicToolName: 'music_create',
        createMusicAsyncToolName: 'music_create_async',
        getMusicAsyncToolName: 'music_get_async',
        description: 'ATXP Music MCP server',
        getArguments: (prompt: string, lyrics: string) => ({ prompt, lyrics }),
        getResult: (result: any) => {
          const jsonResult = result.content[0].text;
          const parsed = JSON.parse(jsonResult);
          return { status: parsed.status, url: parsed.url };
        },
        getAsyncCreateResult: (result: any) => {
          const jsonResult = result.content[0].text;
          const parsed = JSON.parse(jsonResult);
          return { taskId: parsed.taskId };
        },
        getAsyncStatusResult: (result: any) => {
          const jsonResult = result.content[0].text;
          const parsed = JSON.parse(jsonResult);
          return { status: parsed.status, url: parsed.url, createdAt: parsed.createdAt, completedAt: parsed.completedAt, errorMessage: parsed.errorMessage };
        }
      };
    ```
  </Step>

  <Step title="Create an ATXP client">
    <Tabs>
      <Tab title="Using an ATXP account">
        Create a client using an <a href="/developers/build-agents/create-account" target="_blank">ATXP account</a> by importing the ATXP client SDK and other dependencies.

        ```typescript theme={null}
        // Import the ATXP client SDK
        import { atxpClient, ATXPAccount } from '@atxp/client';

        // Read the ATXP account details from environment variables
        const atxpConnectionString = process.env.ATXP_CONNECTION;

        // Create a client using the `atxpClient` function
        const client = await atxpClient({
          mcpServer: musicService.mcpServer,
          account: new ATXPAccount(atxpConnectionString),
        });
        ```
      </Tab>

      <Tab title="Using a Base account">
        Create a client using a Base account by importing the ATXP client SDK and other dependencies.

        ```typescript theme={null}
        // Import the ATXP client SDK and Base account
        import { atxpClient } from '@atxp/client';
        import { BaseAccount } from '@atxp/base';

        // Read the Base account details from the environment variables
        const baseRpcUrl = process.env.BASE_RPC_URL;
        const basePrivateKey = process.env.BASE_PRIVATE_KEY;

        // Create a client using the `atxpClient` function
        const client = await atxpClient({
          mcpServer: musicService.mcpServer,
          account: new BaseAccount(baseRpcUrl, basePrivateKey),
        });
        ```
      </Tab>

      <Tab title="Using a Solana account">
        Create a client using a Solana account by importing the ATXP client SDK and other dependencies.

        ```typescript theme={null}
        // Import the ATXP client SDK and Solana account
        import { atxpClient } from '@atxp/client';
        import { SolanaAccount } from '@atxp/solana';

        // Read the Solana account details from the environment variables
        const solanaRpcUrl = process.env.SOLANA_RPC_URL;
        const solanaPrivateKey = process.env.SOLANA_PRIVATE_KEY;

        // Create a client using the `atxpClient` function
        const client = await atxpClient({
          mcpServer: musicService.mcpServer,
          account: new SolanaAccount(solanaRpcUrl, solanaPrivateKey),
        });
        ```
      </Tab>

      <Tab title="Using a Worldchain account">
        Create a client using a Worldchain account with MiniKit integration.

        ```typescript theme={null}
        // Import the ATXP client SDK and Worldchain account creator
        import { atxpClient } from '@atxp/client';
        import { createMiniKitWorldchainAccount } from '@atxp/worldchain';
        import { MiniKit } from '@worldcoin/minikit-js';

        // Create a Worldchain account using MiniKit
        const account = await createMiniKitWorldchainAccount({
          walletAddress: '0x1234...', // User's wallet address
          miniKit: MiniKit
        });

        // Create a client using the `atxpClient` function
        const client = await atxpClient({
          mcpServer: musicService.mcpServer,
          account,
        });
        ```
      </Tab>

      <Tab title="Using a Polygon account">
        **Browser applications:**

        ```typescript theme={null}
        // Import the ATXP client SDK and Polygon browser account
        import { atxpClient } from '@atxp/client';
        import { PolygonBrowserAccount } from '@atxp/polygon';

        // Initialize the Polygon browser account with wallet provider
        const account = await PolygonBrowserAccount.initialize({
          provider: window.ethereum, // or any EIP-1193 provider
          walletAddress: '0x1234...', // User's wallet address
        });

        // Create a client using the `atxpClient` function
        const client = await atxpClient({
          mcpServer: musicService.mcpServer,
          account,
        });
        ```

        **Server/CLI applications:**

        ```typescript theme={null}
        // Import the ATXP client SDK and Polygon server account
        import { atxpClient } from '@atxp/client';
        import { PolygonServerAccount } from '@atxp/polygon';

        // Read the Polygon account details from the environment variables
        const polygonRpcUrl = process.env.POLYGON_RPC_URL;
        const polygonPrivateKey = process.env.POLYGON_PRIVATE_KEY;

        // Create a Polygon server account
        const account = new PolygonServerAccount(
          polygonRpcUrl,
          polygonPrivateKey,
          137 // Chain ID: 137 = Polygon mainnet, 80002 = Amoy testnet
        );

        // Create a client using the `atxpClient` function
        const client = await atxpClient({
          mcpServer: musicService.mcpServer,
          account,
        });
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Use the Music service in your agent">
    <Tabs>
      <Tab title="Synchronous Generation">
        Call the Music tool by passing your natural-language instruction as the argument the `getArguments` method.

        Read the response using the `getResult` method.

        ```typescript theme={null}
        const prompt = "polka, upbeat, fast";
        const lyrics = "[intro]Hey there cowboy[verse]That's a mighty fine horse you got[outro]";

        try {
          const result = await client.callTool({
              name: musicService.createMusicToolName,
              arguments: musicService.getArguments(prompt, lyrics),
          });
          const { status, url } = musicService.getResult(result);
          console.log('Status:', status);
          console.log('URL:', url);
        } catch (error) {
          console.error(`Error with ${musicService.description}:`, error);
          process.exit(1);
        }
        ```

        <Check>
          You should see the result of the music creation printed in your console.
        </Check>
      </Tab>

      <Tab title="Asynchronous Generation">
        For longer music generation tasks (which can take 1-3 minutes), use the async tools to avoid blocking your application. Start the generation and poll for completion.

        ```typescript theme={null}
        const prompt = "polka, upbeat, fast";
        const lyrics = "[intro]Hey there cowboy[verse]That's a mighty fine horse you got[outro]";

        try {
          // Start async music generation
          const asyncResult = await client.callTool({
              name: musicService.createMusicAsyncToolName,
              arguments: musicService.getArguments(prompt, lyrics),
          });
          const { taskId } = musicService.getAsyncCreateResult(asyncResult);
          console.log('Task started with ID:', taskId);

          // Poll for completion
          let completed = false;
          while (!completed) {
            await new Promise(resolve => setTimeout(resolve, 10000)); // Wait 10 seconds
            
            const statusResult = await client.callTool({
                name: musicService.getMusicAsyncToolName,
                arguments: { taskId },
            });
            const { status, url, errorMessage } = musicService.getAsyncStatusResult(statusResult);
            
            console.log('Status:', status);
            
            if (status === 'completed') {
              console.log('URL:', url);
              completed = true;
            } else if (status === 'error') {
              console.error('Music generation failed:', errorMessage);
              completed = true;
            }
          }
        } catch (error) {
          console.error(`Error with ${musicService.description}:`, error);
          process.exit(1);
        }
        ```

        <Check>
          You should see the task ID printed first, followed by status updates, and finally the music URL when generation completes.
        </Check>
      </Tab>
    </Tabs>
  </Step>
</Steps>
