Skip to main content

Python code interpreter agent tool

Databricks provides system.ai.python_exec, a built-in Unity Catalog function that lets AI agents dynamically run Python code written by the agent, provided by a user, or retrieved from a codebase. It is available by default and can be used directly in a SQL query:

SQL
SELECT python_exec("""
import random
numbers = [random.random() for _ in range(10)]
print(numbers)
""")

To learn more about agent tools, see AI agent tools.

Add the code interpreter to your agent

To add python_exec to your agent, connect to the managed MCP server for the system.ai Unity Catalog schema. The code interpreter is available as a pre-configured MCP tool at https://<workspace-hostname>/api/2.0/mcp/functions/system/ai/python_exec.

Python
from agents import Agent, Runner
from databricks.sdk import WorkspaceClient
from databricks_openai.agents import McpServer

# WorkspaceClient picks up credentials from the environment (Databricks Apps, notebook, CLI)
workspace_client = WorkspaceClient()
host = workspace_client.config.host

# The context manager manages the MCP connection lifecycle and ensures cleanup on exit.
# from_uc_function constructs the endpoint URL from UC identifiers and wires in auth
# from workspace_client, avoiding hardcoded URLs and manual token handling.
async with McpServer.from_uc_function(
catalog="system",
schema="ai",
function_name="python_exec",
workspace_client=workspace_client,
name="code-interpreter",
) as code_interpreter:
agent = Agent(
name="Coding agent",
instructions="You are a helpful coding assistant. Use the python_exec tool to run code.",
model="databricks-claude-sonnet-4-5",
mcp_servers=[code_interpreter],
)
result = await Runner.run(agent, "Calculate the first 10 Fibonacci numbers")
print(result.final_output)

Grant the app access to the function in databricks.yml:

YAML
resources:
apps:
my_agent_app:
resources:
- name: 'python_exec'
uc_securable:
securable_full_name: 'system.ai.python_exec'
securable_type: 'FUNCTION'
permission: 'EXECUTE'

Next steps