Going Headless: Automating with the Python & TypeScript SDKs
Going Headless: Automating with the Python & TypeScript SDKs
Section titled “Going Headless: Automating with the Python & TypeScript SDKs”While Claude Code’s interactive CLI is a powerful pair programmer, its true potential is unlocked when you harness its capabilities programmatically. The Claude Code SDKs for Python and TypeScript allow you to ‘go headless’—integrating its reasoning engine directly into your own scripts, backend services, and CI/CD pipelines, without any user interface.
Headless Mode: The Engine of Automation
Section titled “Headless Mode: The Engine of Automation”‘Headless Mode’ simply means running Claude Code in a non-interactive way, where inputs are provided and outputs are captured for use by another program. This is the foundation of automation. Instead of a human typing prompts, a script sends them. Instead of displaying results in a terminal, they are returned as data structures that your application can act upon.
Common use cases for headless automation include:
- CI/CD Pipelines: Automatically generate documentation, run code reviews, or suggest optimizations for every pull request.
- Custom Dev Tools: Build your own command-line tools that leverage Claude Code for project-specific tasks, like scaffolding a new microservice or migrating legacy code.
- Backend Services: Integrate Claude Code into a larger application to provide intelligent features, such as a bot that can diagnose and report on production issues.
The simplest form of headless mode is using the CLI with the --print (-p) flag. The SDKs provide a more powerful and flexible interface for these same capabilities.
The Python SDK Guide
Section titled “The Python SDK Guide”The Python SDK is perfect for backend development, data science workflows, and scripting. It allows you to interact with Claude Code using familiar Python syntax.
1. Installation
# Ensure you have Claude Code installed first# Then, install the Python SDKpip install claude-code2. Practical Example
Let’s write a simple Python script that uses the SDK to generate a commit message for the current staged changes in a Git repository. This is a classic headless automation task.
import subprocessfrom claude_code import claude_code
def generate_commit_message(): """Generates a commit message for staged changes using Claude Code.""" try: # Get the staged git diff diff = subprocess.check_output(['git', 'diff', '--cached']).decode('utf-8')
if not diff: print("No staged changes to commit.") return
prompt = f"""Based on the following git diff, please write a concise and conventional commit message.
{diff}"""
# Use the SDK to get a response from Claude Code # The run_headless method is the core of the SDK's headless mode response = claude_code.run_headless(prompt)
commit_message = response.result print("Suggested Commit Message:") print("------------------------") print(commit_message)
# You could extend this to automatically commit with the message # subprocess.run(['git', 'commit', '-m', commit_message])
except subprocess.CalledProcessError: print("Error: Not a git repository or no changes staged.") except Exception as e: print(f"An error occurred: {e}")
if __name__ == "__main__": generate_commit_message()The TypeScript SDK Guide
Section titled “The TypeScript SDK Guide”For Node.js backends, custom tooling in the JavaScript ecosystem, or web applications, the TypeScript SDK provides a robust, type-safe way to integrate Claude Code.
1. Installation
# Ensure you have Claude Code installed first# Then, install the TypeScript SDK in your Node.js projectnpm install @anthropic-ai/claude-code2. Practical Example
Let’s create a TypeScript tool that reads a source code file and asks Claude Code to add explanatory comments to it. This script demonstrates reading a file and asking for targeted edits.
import * as fs from 'fs/promises';import { claudeCode } from '@anthropic-ai/claude-code';
async function addCommentsToFile(filePath: string): Promise<void> { try { const fileContent = await fs.readFile(filePath, 'utf-8');
const prompt = `Please add clear and concise comments to the following code to explain its functionality. Return only the fully commented code block.${fileContent}
`;
// The runHeadless method is asynchronous and returns a promise console.log('Asking Claude Code to add comments...'); const response = await claudeCode.runHeadless(prompt);
const commentedCode = response.result;
const newFilePath = `${filePath}.commented.ts`; await fs.writeFile(newFilePath, commentedCode);
console.log(`Successfully created commented file: ${newFilePath}`);
} catch (error) { console.error('An error occurred:', error); }}
// Get the file path from command line argumentsconst filePath = process.argv[2];if (!filePath) { console.error('Please provide a file path as an argument.'); process.exit(1);}
addCommentsToFile(filePath);To run this script, you would save it as commenter.ts, compile it (tsc commenter.ts), and then run it with Node.js: node commenter.js ./path/to/your/file.ts. This headless script performs a useful, automated task, showcasing the power of integrating Claude Code directly into your development tools.