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

> Turn any OpenAPI specification into a code mode MCP server on Blaxel

Blaxel supports "code mode" natively, enabling a more efficient way to execute tool calls over MCP.

<Tip>
  For more information on "code mode" or "code execution with MCP", refer to blog posts by [Cloudflare](https://blog.cloudflare.com/code-mode/) and [Anthropic](https://www.anthropic.com/engineering/code-execution-with-mcp).
</Tip>

The typical flow is:

1. The agent receives a user prompt (e.g. "List all pets")
2. It calls `search` to discover relevant endpoints in the OpenAPI spec
3. It calls `execute` with a `fetch()` script targeting the right endpoint
4. Blaxel spins up a sandbox, injects credentials, and runs the code
5. The result flows back to the agent

Under the hood:

* The agent typically does a search first to find the right endpoint, then executes a `fetch` call.
* When an agent calls `search`, code mode evaluates a JavaScript function against the in-memory OpenAPI specification. All `$ref` pointers are auto-resolved so the agent sees the complete schema.
* When an agent calls `execute`, the code runs inside an auto-scaling sandbox with a 10-minute idle TTL.

## Deployment

Use the following code or Blaxel CLI command to deploy an MCP server in code mode. Replace the `OPENAPI_REFERENCE` variable with the URL to the API specification you want to expose.

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createFunction } from "@blaxel/core";

  async function main() {
    await createFunction({
      body: {
        metadata: {
          name: "my-api-code-mode",
          displayName: "API Code Mode",
        },
        spec: {
          runtime: {
            image: "blaxel/code-mode:latest",
            memory: 2048,
            envs: [
              { name: "OPENAPI_REFERENCE", value: "https://petstore3.swagger.io/api/v3/openapi.json" },
            ],
          },
        },
      },
    });
  }

  main().catch((err) => {
    console.error(err);
    process.exit(1);
  });
  ```

  ```python Python theme={null}
  import asyncio
  import sys

  from blaxel.core.client import client
  from blaxel.core.client.api.functions.create_function import asyncio as create_function
  from blaxel.core.client.models.env import Env
  from blaxel.core.client.models.function import Function
  from blaxel.core.client.models.function_runtime import FunctionRuntime
  from blaxel.core.client.models.function_spec import FunctionSpec
  from blaxel.core.client.models.metadata import Metadata


  async def main():
      await create_function(
          client=client,
          body=Function(
              metadata=Metadata(
                  name="my-api-code-mode",
                  display_name="API Code Mode",
              ),
              spec=FunctionSpec(
                  runtime=FunctionRuntime(
                      image="blaxel/code-mode:latest",
                      memory=2048,
                      envs=[
                          Env(
                              name="OPENAPI_REFERENCE",
                              value="https://petstore3.swagger.io/api/v3/openapi.json",
                          ),
                      ],
                  ),
              ),
          ),
      )


  asyncio.run(main())
  ```

  ```bash Blaxel CLI theme={null}
  bl apply -f - <<EOF
  apiVersion: blaxel.ai/v1alpha1
  kind: Function
  metadata:
    displayName: API Code Mode
    name: my-api-code-mode
  spec:
    runtime:
      type: mcp
      image: blaxel/code-mode:latest
      memory: 2048
      envs:
        - name: OPENAPI_REFERENCE
          value: https://petstore3.swagger.io/api/v3/openapi.json
  EOF
  ```
</CodeGroup>

Check status:

```bash theme={null}
bl get mcp my-api-code-mode
```

Retrieve MCP endpoint url:

```bash theme={null}
bl get mcp my-api-code-mode -o json | jq -r '.[] | .metadata.url'
```

Once status shows `DEPLOYED`, any agent can use the MCP server as a tool provider.

## Authentication

Code mode MCP servers auto-detects security schemes defined in the OpenAPI spec and maps them to environment variables named `AUTH_<SCHEME_NAME>`. For example, if the spec defines a scheme called `ApiKeyAuth`, define an environment variable in your deployment schema called `AUTH_APIKEYAUTH` with the corresponding secret:

```yaml theme={null}
    envs:
      - name: OPENAPI_REFERENCE
        value: https://api.example.com/openapi.json
      - name: AUTH_APIKEYAUTH
        value: ${secrets.AUTH_APIKEYAUTH}
```

### Supported auth types

| OpenAPI scheme type        | Env var usage                    |
| -------------------------- | -------------------------------- |
| `http` / `bearer`          | `Authorization: Bearer <token>`  |
| `http` / `basic`           | `Authorization: Basic <base64>`  |
| `apiKey` (header)          | Custom header with the key value |
| `apiKey` (query)           | Appended as query parameter      |
| `oauth2` / `openIdConnect` | `Authorization: Bearer <token>`  |

<Card title="Use Claude Agent SDK with MCP code mode on Blaxel" icon="thumbs-up" href="/Tutorials/Claude-Agent-SDK-Code-Mode">
  Build an agent that connects to a Blaxel MCP server running in code mode using Claude Agent SDK.
</Card>
