⚙️Code Execution Tool
Let Claude write and run code in a sandboxed environment
Code Execution Tool
What if Claude could not only write code, but also run it and give you the results? That is exactly what the Code Execution tool does. Instead of copying code and running it yourself, Claude writes it, runs it, and gives you the result directly.
What is the Code Execution Tool?
The Code Execution tool gives Claude the ability to:
- Write Python code and execute it immediately
- Process data — read CSV, Excel, and JSON files
- Perform calculations — precise math and statistics
- Create charts and visual graphs
- Transform data from one format to another
- Verify results instead of guessing
The key difference from regular requests: instead of Claude saying "the answer is approximately 42", it actually computes the answer and gives you the exact result.
How to Enable the Code Execution Tool
In the API
{
"model": "claude-sonnet-4-20250514",
"max_tokens": 4096,
"tools": [
{
"type": "code_execution_20250522",
"name": "code_execution"
}
],
"messages": [
{
"role": "user",
"content": "Calculate the standard deviation of: 4, 8, 15, 16, 23, 42"
}
]
}Using the JavaScript SDK
const client = new Anthropic();
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [
{
type: "code_execution_20250522",
name: "code_execution",
},
],
messages: [
{
role: "user",
content: "Calculate the standard deviation of: 4, 8, 15, 16, 23, 42",
},
],
});
console.log(response.content);Using the Python SDK
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=[
{
"type": "code_execution_20250522",
"name": "code_execution",
}
],
messages=[
{
"role": "user",
"content": "Calculate the standard deviation of: 4, 8, 15, 16, 23, 42",
}
],
)
print(response.content)Understanding the Response
When Claude uses the Code Execution tool, the response contains several types of blocks:
{
"content": [
{
"type": "thinking",
"text": "I will write Python code to calculate the standard deviation..."
},
{
"type": "server_tool_use",
"id": "srvtoolu_abc123",
"name": "code_execution",
"input": {
"code": "import statistics\nnumbers = [4, 8, 15, 16, 23, 42]\nstd_dev = statistics.stdev(numbers)\nprint(f'Standard deviation: {std_dev:.4f}')"
}
},
{
"type": "code_execution_result",
"output": {
"type": "text",
"text": "Standard deviation: 13.2841"
}
},
{
"type": "text",
"text": "The standard deviation of the numbers is 13.2841"
}
]
}Important note: Unlike regular tools, the Code Execution tool is executed server-side — you do not need to execute anything yourself. Anthropic handles running the code in a secure environment.
Practical Use Cases
1. Precise Mathematical Calculations
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [{ type: "code_execution_20250522", name: "code_execution" }],
messages: [
{
role: "user",
content:
"I have a loan of $500,000, at 4.5% annual interest, for 25 years. " +
"Calculate: the monthly payment, total payments, and total interest",
},
],
});Claude will write Python code to calculate the loan precisely using mathematical financial formulas instead of guessing.
2. CSV Data Analysis
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [{ type: "code_execution_20250522", name: "code_execution" }],
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Analyze this file and give me: mean, median, highest and lowest value for each numeric column",
},
{
type: "document",
source: {
type: "base64",
media_type: "text/csv",
data: "bmFtZSxhZ2Usc2FsYXJ5CkFobWVkLDMwLDUwMDAKU2FyYSwsMjUsNDUwMApNb2hhbWVkLDM1LDcwMDA=",
},
title: "employees.csv",
},
],
},
],
});Claude will use pandas to analyze the data and give you precise statistics.
3. Creating Charts
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [{ type: "code_execution_20250522", name: "code_execution" }],
messages: [
{
role: "user",
content:
"Create a chart showing the company's monthly sales: " +
"January: 50000, February: 62000, March: 45000, " +
"April: 71000, May: 58000, June: 89000",
},
],
});
// The response will contain a base64 image of the chart
for (const block of response.content) {
if (block.type === "code_execution_result" && block.output.type === "image") {
console.log("Chart image:", block.output.data.slice(0, 50) + "...");
}
}Claude will use matplotlib to create a beautiful chart and return it as an image.
4. Data Transformation
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [{ type: "code_execution_20250522", name: "code_execution" }],
messages: [
{
role: "user",
content:
'Convert this JSON to a CSV table and add a "Total" column: ' +
JSON.stringify([
{ product: "Coffee", price: 15, quantity: 100 },
{ product: "Tea", price: 10, quantity: 200 },
{ product: "Juice", price: 20, quantity: 75 },
]),
},
],
});Combining with Web Search
You can combine the Code Execution tool with the Web Search tool to get fresh data and analyze it:
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [
{ type: "code_execution_20250522", name: "code_execution" },
{ type: "web_search_20250305", name: "web_search" },
],
messages: [
{
role: "user",
content:
"Search for the stock prices of the top 5 tech companies today " +
"then create a chart comparing them",
},
],
});Claude will search for the data first, then use code to analyze it and create a chart.
Execution Environment Details (Sandbox)
┌─────────────────────────────────────────────────┐
│ Code Execution Environment │
│ │
│ 🐍 Language: Python only │
│ 📦 Pre-installed Libraries: │
│ • pandas — data analysis │
│ • numpy — numerical operations │
│ • matplotlib — charts and graphs │
│ • seaborn — advanced visualizations │
│ • scipy — scientific computing │
│ • sympy — symbolic mathematics │
│ • statistics — basic statistics │
│ │
│ ⏱️ Timeout: 30 seconds per execution │
│ 💾 Memory: Limited for security reasons │
│ 🌐 Internet: No direct access │
│ 📁 Files: Can only read from attachments │
└─────────────────────────────────────────────────┘
Note: The environment is completely isolated — code cannot access the internet or your personal files.
Pricing
The Code Execution tool has a special pricing model:
| Item | Details |
|---|---|
| With web search | Free — no additional cost |
| Without web search | Counted as regular input/output tokens |
| Executed code | Counted as input tokens |
| Results | Counted as output tokens |
| Generated images | Counted as additional output tokens |
Important Limitations
What the Tool Cannot Do
- No internet access — cannot download files from the web during execution
- Python only — cannot run JavaScript or other languages
- Timeout — code must finish within 30 seconds
- Limited memory — cannot process very large files
- No persistent storage — data is lost after the session ends
- Limited libraries — only pre-installed libraries are available
Tips for Best Results
- Be specific about what you want — "Calculate the mean and median" is better than "analyze the data"
- Attach the data directly in the request instead of describing it
- Request charts — the Code Execution tool excels at visual representation
- Use it for verification — if you doubt a Claude answer, ask it to verify with code
Advanced Examples
Example 1: Text Analysis (Simple NLP)
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [{ type: "code_execution_20250522", name: "code_execution" }],
messages: [
{
role: "user",
content:
"Analyze this text and give me: word count, top 10 most frequent words, " +
"and a chart of sentence length distribution:\n\n" +
"Artificial intelligence is changing the world. Companies are investing in AI. " +
"The future depends on artificial intelligence and technology. " +
"Machine learning is an important part of artificial intelligence.",
},
],
});Example 2: Complex Financial Calculations
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
tools=[{"type": "code_execution_20250522", "name": "code_execution"}],
messages=[
{
"role": "user",
"content": (
"I have an investment portfolio: "
"Stock A: $10,000 at 8% return, "
"Stock B: $15,000 at 12% return, "
"Bonds: $25,000 at 5% return. "
"Calculate: weighted return, value after 5 and 10 years "
"(with reinvestment), and create a chart showing "
"portfolio growth over 10 years"
),
}
],
)
for block in response.content:
if hasattr(block, "text"):
print(block.text)
elif block.type == "code_execution_result":
if block.output.type == "image":
print("[Chart generated]")
else:
print("Result:", block.output.text)Example 3: Data Cleaning and Transformation
const messyData = `
Name,Email,Phone,Date
Ahmed, ahmed@gmail.com , 0501234567, 2024-01-15
sara,SARA@YAHOO.COM, 050-123-4567 , 01/15/2024
MOHAMED, mohamed@hotmail.com,+966501234567,January 15, 2024
`;
const response = await client.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 4096,
tools: [{ type: "code_execution_20250522", name: "code_execution" }],
messages: [
{
role: "user",
content:
"Clean this data: " +
"1. Standardize name format (capitalize first letter) " +
"2. Clean emails (lowercase, no spaces) " +
"3. Standardize phone format (+966XXXXXXXXX) " +
"4. Standardize date format (YYYY-MM-DD)\n\n" +
messyData,
},
],
});Processing Execution Results
function processCodeExecutionResponse(response) {
const results = {
text: [],
images: [],
code: [],
errors: [],
};
for (const block of response.content) {
switch (block.type) {
case "text":
results.text.push(block.text);
break;
case "server_tool_use":
if (block.name === "code_execution") {
results.code.push(block.input.code);
}
break;
case "code_execution_result":
if (block.output.type === "text") {
results.text.push(block.output.text);
} else if (block.output.type === "image") {
results.images.push({
format: block.output.media_type,
data: block.output.data,
});
}
// Check for errors
if (block.is_error) {
results.errors.push(block.output.text);
}
break;
}
}
return results;
}
// Using the function
const processed = processCodeExecutionResponse(response);
console.log("Text outputs:", processed.text);
console.log("Number of images:", processed.images.length);
console.log("Errors:", processed.errors);Comparison: When to Use Code Execution vs Alternatives
┌────────────────────────────────────────────────────────────┐
│ When to Use the Code Execution Tool? │
│ │
│ ✅ Use it for: │
│ • Precise calculations (financial, statistical, math) │
│ • Data analysis (CSV, JSON, Excel) │
│ • Creating charts and visualizations │
│ • Data cleaning and transformation │
│ • Verifying results with code │
│ │
│ ❌ Do NOT use it for: │
│ • Simple questions that do not need computation │
│ • Writing code for your project (just ask for the code) │
│ • Tasks that need internet (use web_search) │
│ • Running non-Python code │
│ • Processing very large files (beyond memory limits) │
└────────────────────────────────────────────────────────────┘
Summary
| Aspect | Details |
|---|---|
| What it is | A tool that lets Claude write and execute Python code |
| Execution | Server-side — no local setup needed |
| Language | Python only |
| Libraries | pandas, numpy, matplotlib, scipy, and more |
| Pricing | Free with web search |
| Timeout | 30 seconds per execution |
| Best for | Precise calculations, data analysis, charts |
Next: We will learn about custom tools — how to build your own tools and give them to Claude.