Execute code on Databricks clusters using MCP Command Execution API. Supports stateless quick validation and stateful iterative development. Use when testing Python/SQL code on clusters, debugging pipelines, or validating transformations.
Execute and test code directly on Databricks clusters using the Model Context Protocol (MCP) Command Execution API. This skill handles both quick validations and interactive development sessions.
Stateless (databricks_command MCP tool):
Stateful (context-based execution):
Use when you need to run a single operation without maintaining state.
Pattern:
databricks_command MCP tool with:
cluster_id: Target Databricks clusterlanguage: "python" or "sql"code: The code to executeExample:
# User request: "Test this SQL query on my cluster"
# Code to execute:
SELECT COUNT(*) as total_records
FROM my_catalog.my_schema.transactions
WHERE date >= current_date() - INTERVAL 7 DAY
Claude calls databricks_command MCP tool → Executes on cluster → Returns result count.
Use when you need multiple operations that build on each other.
Pattern:
create_context MCP tool:
cluster_id: Target clusterlanguage: "python" (default)context_idexecute_command_with_context for each code block:
cluster_id: Same clustercontext_id: From step 2code: Code to executedestroy_context:
cluster_id: Same clustercontext_id: To clean upExample:
# User request: "Test this multi-step data transformation"
# Step 1: Create context
context_id = create_context(cluster_id="0123-456789-abc123", language="python")
# Step 2: Load data (context persists)
execute_command_with_context(
cluster_id="0123-456789-abc123",
context_id=context_id,
code="""
from pyspark.sql import functions as F
df = spark.table("my_catalog.my_schema.raw_data")
print(f"Loaded {df.count()} records")
"""
)
# Step 3: Transform (uses df from step 2)
execute_command_with_context(
cluster_id="0123-456789-abc123",
context_id=context_id,
code="""
clean_df = df.filter(F.col("id").isNotNull()).dropDuplicates(["id"])
print(f"Clean records: {clean_df.count()}")
clean_df.show(5)
"""
)
# Step 4: Cleanup
destroy_context(cluster_id="0123-456789-abc123", context_id=context_id)
Use for fixing code based on cluster errors.
Pattern:
Common Errors and Fixes:
| Error Type | Cause | Solution |
|------------|-------|----------|
| NameError | Variable not defined | Check if using stateful context, ensure variable defined in prior call |
| AnalysisException | Table/column not found | Verify full table name (catalog.schema.table), check column spelling |
| Py4JJavaError | Spark operation failed | Check data types, null handling, add filters to reduce data |
| Timeout (120s) | Code took too long | Break into smaller chunks, add limits, optimize query |
LIMIT 100)print() liberally for debugging.show(5)Critical Rules:
databricks-ml-pipeline - Tests ML training codedatabricks-data-engineering - Tests ETL transformationsdatabricks-bundle-deploy - Once code works, package as DABdatabricks-unity-catalog - Tests against UC tables# User: "Validate this aggregation query"
# Stateless execution via databricks_command
databricks_command(
cluster_id="0123-456789-abc123",
language="sql",
code="""
SELECT
customer_id,
COUNT(*) as order_count,
SUM(amount) as total_spent
FROM my_catalog.sales.orders
WHERE order_date >= '2024-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5
LIMIT 10
"""
)
# Returns: Query results with top 10 customers
# User: "Test this data cleaning code"
# Stateless execution
databricks_command(
cluster_id="0123-456789-abc123",
language="python",
code="""
from pyspark.sql import functions as F
# Load sample
df = spark.table("my_catalog.bronze.raw_events").limit(1000)
# Clean
clean_df = (
df
.filter(F.col("event_id").isNotNull())
.filter(F.col("timestamp").isNotNull())
.withColumn("amount", F.col("amount").cast("double"))
)
print(f"Original: {df.count()} rows")
print(f"Clean: {clean_df.count()} rows")
print(f"Removed: {df.count() - clean_df.count()} rows")
clean_df.show(5)
"""
)
# Returns: Row counts and sample data
# User: "Help me build features for ML model"
# Create stateful context
context_id = create_context(
cluster_id="0123-456789-abc123",
language="python"
)
# Step 1: Load and explore
execute_command_with_context(
cluster_id="0123-456789-abc123",
context_id=context_id,
code="""
df = spark.table("my_catalog.ml.customer_data")
print(f"Total customers: {df.count()}")
print(f"Columns: {df.columns}")
df.describe().show()
"""
)
# Step 2: Create features (df persists from step 1)
execute_command_with_context(
cluster_id="0123-456789-abc123",
context_id=context_id,
code="""
from pyspark.sql import functions as F
from pyspark.sql.window import Window
# Time-based features
w = Window.partitionBy("customer_id").orderBy("transaction_date")
features_df = (
df
.withColumn("days_since_last",
F.datediff(F.current_date(), F.col("transaction_date")))
.withColumn("transaction_count",
F.count("*").over(w))
.withColumn("avg_amount",
F.avg("amount").over(w))
)
print("Features created:")
features_df.select("customer_id", "days_since_last", "transaction_count", "avg_amount").show(10)
"""
)
# Step 3: Validate features
execute_command_with_context(
cluster_id="0123-456789-abc123",
context_id=context_id,
code="""
# Check for nulls
null_counts = features_df.select([
F.sum(F.when(F.col(c).isNull(), 1).otherwise(0)).alias(c)
for c in features_df.columns
])
print("Null counts by column:")
null_counts.show()
# Validate ranges
print("\\nFeature statistics:")
features_df.select("days_since_last", "transaction_count", "avg_amount").describe().show()
"""
)
# Cleanup
destroy_context(
cluster_id="0123-456789-abc123",
context_id=context_id
)
# User: "Check if cluster has required libraries"
databricks_command(
cluster_id="0123-456789-abc123",
language="python",
code="""
# Test imports
try:
import pandas as pd
import numpy as np
import mlflow
import sklearn
print("✓ All required libraries available")
print(f" pandas: {pd.__version__}")
print(f" numpy: {np.__version__}")
print(f" mlflow: {mlflow.__version__}")
print(f" sklearn: {sklearn.__version__}")
except ImportError as e:
print(f"✗ Missing library: {e}")
print(" Use: %pip install <library>")
# Check Spark version
print(f"\\n✓ Spark version: {spark.version}")
"""
)
# Returns: Library versions or installation instructions
Error: "Context with id X does not exist"
Causes:
Solution:
Error: "Command timed out after 120 seconds"
Causes:
Solution:
LIMIT to queries during testingError: NameError: name 'df' is not defined
Causes:
Solution:
This skill enables rapid testing and iteration on Databricks clusters via MCP:
Use this skill to validate code before packaging with databricks-bundle-deploy.
npx skills add databricks-solutions/databricks-testing下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer