Let agents run code

Important

To use system.ai.dbsql, system.ai.sandbox, or system.ai.web_search, an account admin must enable the Unity Gateway beta from the account console Previews page. See Manage account previews.

Use the system.ai.sandbox MCP to let your agent run Python, SQL, or shell code in an isolated environment. 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

Install the libraries:

pip install --upgrade databricks-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_core.messages import convert_to_openai_messages
from langgraph.prebuilt import create_react_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_react_agent(
        ChatDatabricks(endpoint="databricks-claude-sonnet-4-5"),
        tools=await mcp_client.get_tools(),
        prompt=lambda state: convert_to_openai_messages(state["messages"]),
    )
    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. The sandbox MCP does not have network egress, so use code that does not need to download packages or call external APIs.

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 legacy workspace endpoint permissions. For agent deployment and function access, see Agent authentication.

Additional resources