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

# Code generation tools

> Tools and functions that are optimized for AI codegen use cases.

Blaxel Sandboxes provide tools for managing files and their contents, specialized for code generation ("*codegen*") use cases. These tools are accessible through the sandboxes' [MCP server](https://docs.blaxel.ai/Sandboxes/Overview#mcp-server-for-a-sandbox) and [REST API](https://docs.blaxel.ai/api-reference/root/welcome-message).

## Fast apply of file edits

<Note>
  Fast apply of file edits is powered by [Morph](https://morphllm.com/) or [Relace](https://www.relace.ai/) and requires you to bring your own Morph/Relace account.
</Note>

With this tool, you can **apply code changes** suggested by an LLM to your existing code files fast (2000+ tokens/second).

Traditional code generation requires generating the entire files every time, which can be slower for large files. With this approach your LLM only generates the specific changes needed, and this tool applies them to the original file.

### Configure environment variables

<Tabs>
  <Tab title="Morph">
    Pass your [Morph API key](https://docs.morphllm.com/api-reference/introduction#authentication) and Morph model (default = *morph-v2*) set as environment variables when creating the sandbox.

    <CodeGroup>
      ```tsx TypeScript theme={null}

      import { SandboxInstance } from "@blaxel/core";

      // Create sandbox with Morph API key for fast code edits
      const sandbox = await SandboxInstance.createIfNotExists({
        name: "codegen-sandbox",
        image: "blaxel/nextjs:latest",
        memory: 4096,
        region: "us-pdx-1",
        ports: [
          { name: "preview", target: 3000 }
        ],
        envs: [
          { name: "MORPH_API_KEY", value: process.env.MORPH_API_KEY || "" },
          { name: "MORPH_MODEL", value: process.env.MORPH_MODEL || "morph-v2" }
        ]
      });

      ```

      ```python Python theme={null}

      import os
      from blaxel.core import SandboxInstance

      # Create sandbox with Morph/Relace API key for fast code edits
      sandbox = await SandboxInstance.create_if_not_exists({
        "name": "codegen-sandbox",
        "image": "blaxel/nextjs:latest",
        "memory": 4096,
        "region": "us-pdx-1",
        "ports": [
          { "name": "preview", "target": 3000 }
        ],
        "envs": [
          { "name": "MORPH_API_KEY", "value": os.getenv("MORPH_API_KEY") },
          { "name": "MORPH_MODEL", "value": os.getenv("MORPH_MODEL") or "morph-v2" }
        ]
      })

      ```
    </CodeGroup>
  </Tab>

  <Tab title="Relace">
    Pass your [Relace API key](https://docs.relace.ai/api-reference/introduction#authentication) as an environment variable when creating the sandbox.

    <CodeGroup>
      ```tsx TypeScript theme={null}

      import { SandboxInstance } from "@blaxel/core";

      // Create sandbox with Relace API key for fast code edits
      const sandbox = await SandboxInstance.createIfNotExists({
        name: "codegen-sandbox",
        image: "blaxel/nextjs:latest",
        memory: 4096,
        region: "us-pdx-1",
        ports: [
          { name: "preview", target: 3000 }
        ],
        envs: [
          { name: "RELACE_API_KEY", value: process.env.RELACE_API_KEY || "" }
        ]
      });
      ```

      ```python Python theme={null}

      import os
      from blaxel.core import SandboxInstance

      # Create sandbox with Relace API key for fast code edits
      sandbox = await SandboxInstance.create_if_not_exists({
        "name": "codegen-sandbox",
        "image": "blaxel/nextjs:latest",
        "memory": 4096,
        "region": "us-pdx-1",
        "ports": [
          { "name": "preview", "target": 3000 }
        ],
        "envs": [
          { "name": "RELACE_API_KEY", "value": os.getenv("RELACE_API_KEY") },
        ]
      })
      ```
    </CodeGroup>
  </Tab>
</Tabs>

### Use the tool via Blaxel SDK

Call the `fastapply` endpoint of the [Sandbox API](https://docs.blaxel.ai/api-reference/fastapply/apply-code-edit) via the Blaxel SDK to fast-apply a targeted edit to a specified file with Morph or Relace, with instructions and partial contents.

<CodeGroup>
  ```typescript TypeScript theme={null}

  import { SandboxInstance } from "@blaxel/core";

  // Apply code changes
  await sandbox.codegen.fastapply(
    "/tmp/test.ts",
    "// keep existing code // add a typescript function to calculate the area of a circle"
  );

  // Read file with changes
  let content = await sandbox.fs.read("/tmp/test.ts");
  console.log(content)
  ```

  ```python Python theme={null}

  from blaxel.core import SandboxInstance

  logger = logging.getLogger(__name__)

  # Apply code changes
  await sandbox.codegen.fastapply(
      "/tmp/test.ts",
      "// keep existing code // add a typescript function to calculate the area of a circle;"
  )

  # Read file with changes
  content = await sandbox.fs.read("/tmp/test.ts")
  logger.info(content)
  ```
</CodeGroup>

### Use the tool via MCP

Call the `codegenEditFile` tool on the **[MCP server of a sandbox](https://docs.blaxel.ai/Sandboxes/Overview#mcp-server-for-a-sandbox)** to fast-apply a targeted edit to a specified file, with instructions and partial contents.

Use Blaxel SDK to retrieve the tool in any [compatible agent framework](../Tutorials/Agents-Overview) (here in AI SDK format):

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { blTools } from '@blaxel/vercel';

  // Get codegen tools from sandbox MCP
  const allTools = await blTools([`sandboxes/${sandbox.metadata.name}`]);

  // Filter for specific codegen tools
  const codegenTools = Object.fromEntries(
    Object.entries(allTools).filter(([key]) =>
      key.startsWith('codegen')
    )
  );
  ```

  ```python Python theme={null}
  from blaxel.langgraph import bl_tools

  # Get codegen tools from sandbox MCP
  all_tools = await bl_tools([f"sandboxes/{sandbox.metadata.name}"])

  # Filter for specific codegen tools
  codegen_tools = [tool for tool in all_tools if tool.name.startswith("codegen")]
  ```
</CodeGroup>

## Other tools built for codegen

Use the following codegen-optimized functions by making tool calls through the MCP server or REST API of a sandbox. See example above on how to retrieve and execute the tools.

| Tool                    | Description                                                     |
| ----------------------- | --------------------------------------------------------------- |
| `codegenCodebaseSearch` | Semantic search to find relevant code snippets                  |
| `codegenFileSearch`     | Fast fuzzy file path search                                     |
| `codegenGrepSearch`     | Exact regex search using ripgrep engine                         |
| `codegenListDir`        | List directory contents (quick discovery)                       |
| `codegenReadFileRange`  | Read file contents within a specific line range (max 250 lines) |
| `codegenRerank`         | Performs semantic search/reranking on code files in a directory |
| `codegenParallelApply`  | Plan parallel edits across multiple file locations              |
| `codegenReapply`        | Use smarter model to retry a failed edit                        |

<Card title="Connect Claude Code to a Blaxel Sandbox" icon="cube" iconType="light" href="../Tutorials/Claude-Agent-SDK-MCP">
  Build a Claude Agent SDK agent that connects to a Blaxel sandbox and operates it using the sandbox's MCP server.
</Card>
