Claude Agent SDK
The Claude Agent SDK is Anthropic's official SDK for building production-ready AI agents with Claude. Braintrust supports tracing agent queries and tool executions.
pnpm add braintrust @anthropic-ai/claude-agent-sdk zod
This example sets up Braintrust tracing for the Claude Agent SDK, creates a calculator tool, and runs a multi-step calculation query.
import { initLogger, wrapClaudeAgentSDK } from "braintrust";
import * as claudeSDK from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
// Initialize Braintrust logging
initLogger({
projectName: "claude-agent-example",
apiKey: process.env.BRAINTRUST_API_KEY,
});
// Wrap the Claude SDK with Braintrust tracing.
const { query, tool, createSdkMcpServer } = wrapClaudeAgentSDK(claudeSDK);
// Create a calculator tool
const calculator = tool(
"calculator",
"Performs basic arithmetic operations",
{
operation: z.enum(["add", "subtract", "multiply", "divide"]),
a: z.number(),
b: z.number(),
},
async (args: { operation: string; a: number; b: number }) => {
console.log(`[Tool] Calculating: ${args.a} ${args.operation} ${args.b}`);
let result = 0;
switch (args.operation) {
case "add":
result = args.a + args.b;
break;
case "subtract":
result = args.a - args.b;
break;
case "multiply":
result = args.a * args.b;
break;
case "divide":
if (args.b === 0) {
return {
content: [
{
type: "text",
text: "Error: Division by zero",
},
],
isError: true,
};
}
result = args.a / args.b;
break;
}
return {
content: [
{
type: "text",
text: `The result of ${args.operation}(${args.a}, ${args.b}) is ${result}`,
},
],
};
},
);
async function main() {
console.log("Starting Claude Agent SDK example with Braintrust tracing...\n");
try {
// Query with mcp server for tool calls
const result = query({
prompt: "What is 15 multiplied by 7? Then subtract 5 from the result.",
options: {
model: "claude-3-5-sonnet-20241022",
permissionMode: "bypassPermissions",
mcpServers: {
calculator: createSdkMcpServer({
name: "calculator",
version: "1.0.0",
tools: [calculator],
}),
},
},
});
// Stream the results
for await (const message of result) {
console.log(message);
}
console.log("\n\n✓ Example completed! Check Braintrust for tracing data.");
} catch (error) {
console.error("Error:", error);
process.exit(1);
}
}
main();