> ## 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.

# Code

> Write and execute code

## Overview

Use the Code MCP server from your ATXP-powered agent to run code in a variety of languages in a sandboxed environment.

## Example prompts

* "Run the following python code: print('Hello, world!')"
* "What is the result of this javascript code: console.log('Hello, world!');"
* "What is the result of this Scheme code: (display 'Hello, world!)"

## Tools

<AccordionGroup>
  <Accordion title="code_execute_code">
    Take in code and execute it in a sandbox. The output will be the result of the code execution. An example of how it can be used would be to run code generated by a LLM in a safe environment.

    ### Arguments

    Accepts a JSON object with the following properties:

    <ParamField body="code" type="string" required>
      The code to execute. It will be executed in a sandbox.
    </ParamField>

    <ParamField body="language" type="string">
      The programming language to use for execution (e.g., javascript, python, typescript, etc.). Default is typescript.
    </ParamField>

    ### Response

    Returns a JSON object with the following properties:

    <ResponseField name="status" type="string">
      The status of the code execution. Returns "success" when the code is executed successfully.
    </ResponseField>

    <ResponseField name="output" type="string">
      The output of the code execution.
    </ResponseField>

    <ResponseField name="exitCode" type="number">
      The exit code of the code execution.
    </ResponseField>
  </Accordion>
</AccordionGroup>

## Usage

<Steps>
  <Step title="Define the Code 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 Code tools in a consistent manner.

    ```typescript theme={null}
    const codeService = {
        mcpServer: 'https://code.mcp.atxp.ai/',
        executeCodeToolName: 'code_execute_code',
        description: 'ATXP Code MCP server',
        getArguments: (code: string, language: string) => ({ code, language }),
        getResult: (result: any) => {
          const jsonResult = result.content[0].text
          return JSON.parse(jsonResult);
        }
      };
    ```
  </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: codeService.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: codeService.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: codeService.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: codeService.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: codeService.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: codeService.mcpServer,
          account,
        });
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Use the Code service in your agent">
    Call the Code tool by passing your natural‑language instruction as the argument the `getArguments` method.

    Read the response using the `getResult` method.

    ```typescript theme={null}
    const code = "print('Hello, world!')";
    const language = "python";

    try {
      const result = await client.callTool({
          name: codeService.executeCodeToolName,
          arguments: codeService.getArguments(code, language),
      });
      const result = codeService.getResult(result);
      console.log('Status:', result.status);
      console.log('Output:', result.output);
      console.log('Exit code:', result.exitCode);
    } catch (error) {
      console.error(`Error with ${codeService.description}:`, error);
      process.exit(1);
    }
    ```

    <Check>
      You should see the result of the code printed in your console.
    </Check>
  </Step>
</Steps>
