Claude API CLI Tool Wrapper Example
What a Claude API CLI Wrapper Actually Does
A CLI wrapper around the Claude API is a small command-line program that takes text input (a prompt, a file, piped stdin), sends it to a Claude-compatible endpoint, and prints the response back to the terminal. People search for "claude api cli tool wrapper example" because they want a working script, not a theoretical explanation — something they can copy, run with node claude.js "summarize this", and extend for their own workflow: git commit message generation, log analysis, quick code review, or scripted content generation.
Below is a complete, minimal wrapper you can adapt in under ten minutes, followed by the pieces that matter if you want it to survive real usage: argument parsing, streaming output, error handling, and key management.
The Core Script
This example uses Node.js with no dependencies beyond what ships in a modern runtime (fetch is global since Node 18).
#!/usr/bin/env node
// claude.js — minimal CLI wrapper around a Claude-compatible API
const API_KEY = process.env.CLAUDE_API_KEY;
const API_URL = "https://api.anthropic.com/v1/messages";
async function ask(prompt) {
const res = await fetch(API_URL, {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01"
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }]
})
});
if (!res.ok) {
console.error(`Request failed: ${res.status} ${await res.text()}`);
process.exit(1);
}
const data = await res.json();
console.log(data.content[0].text);
}
const prompt = process.argv.slice(2).join(" ");
if (!prompt) {
console.error("Usage: claude.js <prompt>");
process.exit(1);
}
ask(prompt);
Make it executable with chmod +x claude.js and run it as ./claude.js "explain this error". This covers the happy path, but a wrapper you'll actually keep using needs a few more things.
Reading From Stdin and Files
Most CLI wrappers get used in pipelines, so support stdin:
let input = "";
if (!process.stdin.isTTY) {
for await (const chunk of process.stdin) input += chunk;
}
const prompt = input || process.argv.slice(2).join(" ");
Now git diff | ./claude.js "write a commit message" works the way developers expect from a Unix tool.
Streaming Output
Waiting for a full response before printing anything feels slow for longer outputs. Streaming fixes that by reading the response as server-sent events and printing tokens as they arrive:
const res = await fetch(API_URL, {
method: "POST",
headers: {
"content-type": "application/json",
"x-api-key": API_KEY,
"anthropic-version": "2023-06-01"
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: prompt }]
})
});
for await (const chunk of res.body) {
const lines = chunk.toString().split("\n").filter(Boolean);
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const event = JSON.parse(line.slice(6));
if (event.type === "content_block_delta") {
process.stdout.write(event.delta.text);
}
}
}
This is the same streaming pattern used by most Claude-compatible APIs — parsing SSE and watching for content_block_delta events.
Argument Parsing for Real Flags
Once you want flags like --model, --max-tokens, or --system, use a tiny parser rather than hand-rolling one:
function parseArgs(argv) {
const opts = { model: "claude-3-5-sonnet-20241022", maxTokens: 1024 };
const rest = [];
for (let i = 0; i < argv.length; i++) {
if (argv[i] === "--model") opts.model = argv[++i];
else if (argv[i] === "--max-tokens") opts.maxTokens = Number(argv[++i]);
else if (argv[i] === "--system") opts.system = argv[++i];
else rest.push(argv[i]);
}
opts.prompt = rest.join(" ");
return opts;
}
For anything beyond a few flags, commander or yargs is worth the dependency.
Swapping the Endpoint for a Simpler Setup
The script above talks directly to a Claude API, which means managing a raw key, handling rate limits yourself, and tracking usage manually if you're sharing the tool across a team. If your CLI wrapper is used by more than one person, or deployed into CI, it's often easier to point it at a managed proxy instead.
SubToAPI turns existing Claude access into a standard HTTPS API with sub_live_... application keys, so the same CLI script above works unchanged — you only swap the base URL and header:
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"content-type": "application/json",
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }]
})
});
That's useful for CLI tools shared across a team because each teammate gets their own sub_live_ key with independent usage tracking, instead of one shared secret passed around in a .env file. See the quickstart for setup and streaming docs if you're building the SSE version above.
Packaging It as a Real Command
Once the script works, make it installable:
- Add a
binfield topackage.jsonpointing at your script. - Run
npm linklocally to test it as a global command. - Publish to npm if you want others to
npm install -g your-cli-name.
{
"name": "ask-claude",
"bin": { "ask-claude": "./claude.js" }
}
Now ask-claude "explain this stack trace" works from any directory.
Error Handling You Shouldn't Skip
CLI tools fail silently if you let them. At minimum, handle:
- Missing API key — check
process.envbefore making any request and print a clear message. - Non-200 responses — print status code and body, don't swallow the error.
- Rate limits (429) — back off and retry once or twice before giving up.
- Empty stdin and empty argv — print usage instead of sending an empty prompt.
A wrapper that fails with TypeError: Cannot read property 'text' of undefined instead of a readable message will get abandoned fast.
questions
Do I need the official Anthropic SDK to build a CLI wrapper? No. Since the API is plain HTTPS with JSON, fetch and a bit of SSE parsing are enough. The SDK saves boilerplate but isn't required for a small CLI tool.
Can this wrapper support tool use or function calling? Yes — add a tools array to the request body following the same schema as the Messages API, and handle tool_use content blocks in the response. See tool use docs for the request format.
How do I avoid hardcoding an API key in the script? Read it from an environment variable (process.env.CLAUDE_API_KEY or SUBTOAPI_KEY) and never commit it. For shared tools, a proxy like SubToAPI lets each user hold their own key instead of one shared secret — see pricing for plan options.