import { z } from 'zod/v4'
import { CodebuffClient, getCustomToolDefinition } from '@codebuff/sdk'
import type { AgentDefinition } from '@codebuff/sdk'
// Define the custom tool
const apiFetcherTool = getCustomToolDefinition({
toolName: 'fetch_api_data',
description: 'Fetch data from an API endpoint with optional headers',
// Define input schema with Zod
inputSchema: z.object({
url: z.string().url(),
method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).default('GET'),
headers: z.record(z.string(), z.string()).optional(),
body: z.string().optional(),
}),
// Provide example inputs to help the LLM understand usage
exampleInputs: [
{
url: 'https://api.example.com/data',
method: 'GET'
},
{
url: 'https://api.example.com/users',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John' }),
},
],
// Implement the tool's behavior
execute: async ({ url, method, headers, body }) => {
try {
const response = await fetch(url, {
method,
headers,
body: body ? body : undefined,
})
const data = await response.text()
const status = response.status
return [
{
type: 'json' as const,
value: {
status,
data: data.slice(0, 5000), // Limit response size
message: `API request to ${url} completed with status ${status}`,
},
},
]
} catch (error) {
return [
{
type: 'json' as const,
value: {
error: error instanceof Error ? error.message : 'Unknown error',
message: `Failed to fetch from ${url}`,
},
},
]
}
},
})
// Create an agent that uses this tool
const apiAgent: AgentDefinition = {
id: 'api-tester',
displayName: 'API Tester',
model: 'anthropic/claude-4-sonnet-20250522',
toolNames: ['fetch_api_data'],
instructionsPrompt: 'Test API endpoints and analyze their responses.',
}
// Use the agent with the custom tool
const client = new CodebuffClient({
apiKey: process.env.CODEBUFF_API_KEY,
})
const result = await client.run({
agent: 'api-tester',
agentDefinitions: [apiAgent],
customToolDefinitions: [apiFetcherTool],
prompt: 'Fetch data from https://api.github.com/repos/codebuffai/codebuff',
handleEvent: (event) => {
console.log('Event:', JSON.stringify(event, null, 2))
},
})