Let agents run code

Important

system.ai.dbsql, system.ai.sandbox, and system.ai.web_search are in Beta. To use them, an account admin must enable the Enhanced Unity Gateway preview from the account console Previews page. Unity Gateway itself is generally available. See Manage account previews.

Use the system.ai.sandbox MCP to let your agent run Python or shell (sh) code in an isolated environment. To run SQL, use system.ai.dbsql. This example connects a LangGraph agent to the MCP and asks it to run a calculation in Python.

Before you start

Run code with the sandbox MCP

Create a virtual environment and install the libraries:

python3.12 -m venv .venv
source .venv/bin/activate
pip install --upgrade databricks-langchain langchain langgraph "mcp>=1.24,<2"

Save the following as code_agent.py. WorkspaceClient uses your workspace sign-in to authenticate the MCP connection.

import asyncio
from databricks.sdk import WorkspaceClient
from databricks_langchain import (
    ChatDatabricks,
    DatabricksMCPServer,
    DatabricksMultiServerMCPClient,
)
from langchain.agents import create_agent

workspace_client = WorkspaceClient()
server_url = f"{workspace_client.config.host}/ai-gateway/mcp-services/system.ai.sandbox"

async def main():
    mcp_client = DatabricksMultiServerMCPClient([
        DatabricksMCPServer(
            name="code-interpreter",
            url=server_url,
            workspace_client=workspace_client,
        ),
    ])
    agent = create_agent(
        model=ChatDatabricks(endpoint="databricks-claude-sonnet-4-5"),
        tools=await mcp_client.get_tools(),
    )
    result = await agent.ainvoke({
        "messages": [{
            "role": "user",
            "content": "Run Python code to calculate the mean of [12, 18, 24].",
        }],
    })
    print(result["messages"][-1].content)

asyncio.run(main())

Run the agent:

python code_agent.py

The agent discovers the MCP's tools, runs Python code, and returns a mean of 18. Network access from the sandbox isn't guaranteed and can depend on your workspace configuration, so don't rely on code that downloads packages or calls external APIs.

The MCP provides create_sandbox, run_code, and delete_sandbox tools. When your agent calls run_code without a sandbox_id, the MCP creates a new sandbox and returns its ID. Pass that sandbox_id in later calls to keep Python variables and files between calls. Shell commands share the sandbox's files but not its Python variables. To avoid leaving sandboxes running, have your agent call delete_sandbox when it's done.

For other frameworks, use this server_url with the Python agent examples. For deployment, see Build a custom agent.

Use the Python function through MCP (legacy)

For an existing integration with the system.ai.python_exec function, use the agent example above with this URL instead:

server_url = f"{workspace_client.config.host}/api/2.0/mcp/functions/system/ai/python_exec"

This endpoint requires the Managed MCP Servers workspace preview and access to the underlying function. It uses workspace endpoint permissions. For agent deployment and function access, see Agent authentication.

Additional resources