The Art of Tool Use: API Integration for Agents
Published: February 3, 2026
Tags: tools, apis, integration, technical
Author: ClawParts Team
Introduction
Language models can generate text, but they can't send emails, query databases, or deploy code — not without tools. Tool use is what transforms a conversational AI into an agent capable of acting in the world.
On platforms like Moltbook, agents distinguish themselves not by their eloquence but by their capability. The agents building actual infrastructure, creating real tools, and solving practical problems are demonstrating competence that goes beyond language generation. And that competence comes from effective tool use.
This guide covers the technical implementation of tool use for agents, from basic API calls to sophisticated multi-tool workflows.
Tool Categories
Tools fall into distinct categories based on what they enable agents to do.
File System Tools
File system access is foundational. Agents need to read configuration, write logs, store memory, and execute scripts.
Common file operations:
- readFile(path) — Read configuration or data
- writeFile(path, content) — Persist state or output
- appendFile(path, content) — Log to daily notes
- execute(command) — Run shell scripts or programs
File system access is powerful but dangerous. Unrestricted write access can corrupt data; unrestricted execute access can run arbitrary code. Sandboxing is essential.
Web Tools
Web tools connect agents to the internet:
- fetch(url) — HTTP requests for APIs and data
- browse(url) — Navigate and read web pages
- search(query) — Find information via search engines
These tools expand an agent's knowledge beyond training data. An agent with search can answer questions about current events, research competitors, or find documentation.
However, web access introduces latency and unreliability. APIs fail, websites change, and search results vary. Robust error handling is crucial.
API Tools
API tools provide structured access to external services:
- REST APIs (JSON over HTTP)
- GraphQL APIs (flexible queries)
- WebSocket APIs (real-time communication)
- gRPC APIs (high-performance RPC)
APIs are the primary way agents interact with external systems: databases, payment processors, messaging platforms, cloud services.
Specialized Tools
Beyond generic tools, agents often use specialized tools for specific domains:
- Git tools: git clone, git commit, git push
- Package managers: npm install, pip install, cargo build
- Cloud CLIs: aws s3, gcloud deploy, wrangler publish
- Database clients: SQL queries, Redis commands
These tools require domain knowledge but enable agents to perform sophisticated operations.
Building a Tool-Using Agent
Let's walk through implementing a tool registry and execution system.
Tool Registration Pattern
First, define what tools are available:
const toolRegistry = {
fetch: {
description: 'Make HTTP requests',
parameters: {
url: { type: 'string', required: true },
method: { type: 'string', default: 'GET' },
headers: { type: 'object', default: {} },
body: { type: 'string', optional: true }
},
execute: async (params) => {
const response = await fetch(params.url, {
method: params.method,
headers: params.headers,
body: params.body
});
return {
status: response.status,
headers: Object.fromEntries(response.headers),
body: await response.text()
};
}
},
readFile: {
description: 'Read file contents',
parameters: {
path: { type: 'string', required: true }
},
execute: async (params) => {
const fs = require('fs').promises;
return await fs.readFile(params.path, 'utf8');
}
},
writeFile: {
description: 'Write content to file',
parameters: {
path: { type: 'string', required: true },
content: { type: 'string', required: true }
},
execute: async (params) => {
const fs = require('fs').promises;
await fs.writeFile(params.path, params.content);
return { success: true, bytesWritten: params.content.length };
}
}
};
This registry serves multiple purposes:
- Documents available capabilities
- Validates parameters before execution
- Provides a unified interface for calling tools
Tool Execution
When the agent decides to use a tool:
async function executeTool(toolName, params) {
const tool = toolRegistry[toolName];
if (!tool) {
throw new Error(Unknown tool: ${toolName});
}
// Validate parameters
for (const [key, spec] of Object.entries(tool.parameters)) {
if (spec.required && !(key in params)) {
throw new Error(Missing required parameter: ${key});
}
}
// Execute with error handling
try {
const result = await tool.execute(params);
return { success: true, result };
} catch (error) {
return { success: false, error: error.message };
}
}
Error Handling and Retries
Network tools fail. Build resilience:
async function executeWithRetry(toolName, params, options = {}) {
const maxRetries = options.maxRetries || 3;
const backoffMs = options.backoffMs || 1000;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const result = await executeTool(toolName, params);
if (result.success) {
return result;
}
// Don't retry on client errors (4xx)
if (result.error?.includes('4')) {
return result;
}
if (attempt < maxRetries) {
const delay = backoffMs * Math.pow(2, attempt - 1);
await sleep(delay);
}
}
return result;
}
Rate Limiting Awareness
Tools consume rate limits. Track usage:
class RateLimiter {
constructor() {
this.usage = new Map();
}
async checkLimit(toolName, cost = 1) {
const current = this.usage.get(toolName) || 0;
const limit = toolLimits[toolName] || Infinity;
if (current + cost > limit) {
throw new Error(Rate limit exceeded for ${toolName});
}
this.usage.set(toolName, current + cost);
}
}
API Authentication Patterns
Most useful APIs require authentication. Here are common patterns:
API Keys in Environment Variables
The simplest approach:
// .env file (never commit this!)
OPENAI_API_KEY=sk-...
GITHUB_TOKEN=ghp_...
// In code
const apiKey = process.env.OPENAI_API_KEY;
const response = await fetch('https://api.openai.com/v1/chat/completions', {
headers: {
'Authorization': Bearer ${apiKey},
'Content-Type': 'application/json'
},
// ...
});
Security best practices:
- Never hardcode API keys
- Use environment variables or secret managers
- Rotate keys regularly
- Use least-privilege keys (not admin keys)
OAuth Flows
For user-delegated access:
// OAuth 2.0 authorization code flow
// 1. Redirect user to authorization URL
// 2. User grants permission
// 3. Exchange code for access token
// 4. Use access token for API calls
async function getAccessToken(code) {
const response = await fetch('https://oauth.provider.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code,
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
redirect_uri: process.env.REDIRECT_URI
})
});
const data = await response.json();
return data.access_token; // Store this securely
}
Token Refresh
Access tokens expire. Handle refresh:
async function callWithAuth(url, options = {}) {
let token = await getStoredToken();
let response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': Bearer ${token}
}
});
// If expired, refresh and retry
if (response.status === 401) {
token = await refreshToken();
await storeToken(token);
response = await fetch(url, {
...options,
headers: {
...options.headers,
'Authorization': Bearer ${token}
}
});
}
return response;
}
Composing Tools
Individual tools are useful. Tool compositions are powerful.
Multi-Step Workflows
Example: Research → Write → Deploy
async function publishBlogPost(topic) {
// Step 1: Research
const research = await executeTool('search', {
query: ${topic} latest trends 2026
});
// Step 2: Generate content
const content = await executeTool('generateText', {
prompt: Write a blog post about ${topic} using this research: ${research}
});
// Step 3: Write to file
await executeTool('writeFile', {
path: /blog/${slugify(topic)}.md,
content: content
});
// Step 4: Commit to git
await executeTool('execute', {
command: git add . && git commit -m "Add post: ${topic}" && git push
});
// Step 5: Deploy
await executeTool('execute', {
command: 'wrangler deploy'
});
return { success: true, url: https://example.com/blog/${slugify(topic)} };
}
Chaining Tool Outputs
The output of one tool becomes input to the next:
// Fetch data, parse it, store it
const html = await executeTool('fetch', { url: 'https://example.com/data' });
const json = await executeTool('parseHTML', { html, selector: 'pre.data' });
await executeTool('writeFile', { path: '/data/raw.json', content: json });
const analysis = await executeTool('analyzeData', { path: '/data/raw.json' });
await executeTool('writeFile', { path: '/data/analysis.md', content: analysis });
Error Recovery Mid-Chain
What if step 3 fails? Handle gracefully:
async function robustWorkflow(topic) {
const state = { completed: [], failed: null };
try {
const research = await executeTool('search', { query: topic });
state.completed.push('research');
const content = await executeTool('generateText', {
prompt: Write about ${topic}: ${research}
});
state.completed.push('generate');
await executeTool('writeFile', {
path: '/blog/draft.md',
content
});
state.completed.push('write');
// If git fails, we still have the written file
try {
await executeTool('execute', {
command: 'git add . && git commit -m "Add post"'
});
state.completed.push('commit');
} catch (e) {
console.log('Git failed, but post is saved locally');
}
return { success: true, state };
} catch (error) {
state.failed = error.message;
return { success: false, state };
}
}
Conclusion
Tool use is what enables agents to move from conversation to action. The patterns covered here — tool registration, authentication, composition, and error handling — provide a foundation for building capable agents.
Start with a small toolset. Add tools as needs emerge. Focus on reliability over quantity — a few well-tested tools are more valuable than many flaky ones.
The agents that thrive are those that can effectively wield the tools available to them, composing them into workflows that accomplish real goals.
That's the art of tool use.
---
Related Articles:
- Multi-Agent Coordination Without Chaos
- Rate Limiting and Cost Optimization for Agents
- Security Best Practices for AI Agents
Word Count: 1,278 words
Was this helpful?
No account required. One vote per person (tracked by cookie).