Built-in Tools
What: Pre-built functions integrated into AgentForce ADK
Examples: File operations, web scraping, API calls, system commands
Best For: Common tasks, rapid prototyping, standard workflows
Learn how to leverage built-in tools and Model Context Protocol (MCP) servers to create powerful, capability-enhanced agents that can interact with external systems, files, APIs, and data sources.
Understanding the difference between built-in tools and MCP integration is crucial for building effective agents.
Built-in Tools
What: Pre-built functions integrated into AgentForce ADK
Examples: File operations, web scraping, API calls, system commands
Best For: Common tasks, rapid prototyping, standard workflows
MCP Servers
What: External servers providing tools, resources, and integrations
Examples: GitHub, databases, cloud services, custom APIs
Best For: Complex integrations, enterprise systems, specialized workflows
Hybrid Approach
What: Combining both built-in tools and MCP servers
Benefits: Maximum flexibility and capability coverage
Best For: Production applications, comprehensive automation
The most commonly used tools for file and directory management.
import { AgentForceAgent } from '@agentforce/adk';
const fileAgent = new AgentForceAgent({ name: "FileManager", tools: ["fs_read_file", "fs_write_file", "fs_list_dir"]}) .useLLM("ollama", "devstral") // Excellent for file operations .systemPrompt(` You are a file management assistant. You can read, write, and organize files efficiently. Always provide clear feedback on operations performed. `) .prompt("Read the package.json file, analyze dependencies, and create a summary report");
const result = await fileAgent.output("md");console.log(result);
const projectAnalyzer = new AgentForceAgent({ name: "ProjectAnalyzer", tools: [ "fs_get_file_tree", // Get project structure "fs_find_files", // Find specific files "fs_search_content", // Search within files "fs_read_file" // Read file contents ]}) .useLLM("openrouter", "mistralai/devstral-small-1.1") // Great value for coding .systemPrompt(` You are a project analysis expert. Analyze codebases for structure, patterns, and improvement opportunities. Provide actionable insights and recommendations. `) .prompt("Analyze this TypeScript project structure and identify potential improvements");
const analysis = await projectAnalyzer.output("json");
const report = JSON.parse(analysis);console.log("Project Analysis:", report);
const organizer = new AgentForceAgent({ name: "FileOrganizer", tools: [ "fs_list_dir", "fs_move_file", "fs_write_file", "md_create_ascii_tree" ]}) .useLLM("ollama", "qwen3:8b") // Versatile for organization tasks .systemPrompt(` You are a file organization specialist. Create logical folder structures and move files appropriately. Generate documentation for the organization system used. `) .prompt("Organize the files in ./downloads folder by type and create an index");
const organizationReport = await organizer.run();
Tools for external data fetching and web interactions.
const webScraper = new AgentForceAgent({ name: "WebResearcher", tools: ["web_fetch", "filter_content", "fs_write_file"]}) .useLLM("openrouter", "google/gemini-2.5-flash-lite") // Fast web operations .systemPrompt(` You are a web research specialist. Extract relevant information from web pages. Filter out noise and focus on valuable content. Save findings in well-structured formats. `) .prompt("Research the latest developments in AI safety from reputable sources and create a summary report");
const research = await webScraper.output("md");
// The agent will automatically:// 1. Fetch content from web pages// 2. Filter relevant information// 3. Structure findings// 4. Save to a markdown report
const apiIntegrator = new AgentForceAgent({ name: "APIConnector", tools: ["api_fetch", "filter_content", "fs_write_file"]}) .useLLM("ollama", "deepseek-r1:7b") // Excellent reasoning for API work .systemPrompt(` You are an API integration expert. Fetch data from REST APIs, process responses, and handle errors gracefully. Structure data for further processing and storage. `) .prompt(` Connect to the JSONPlaceholder API: 1. Fetch all users from /users 2. Get posts for the first 3 users from /posts?userId=X 3. Create a summary report with user profiles and their post statistics `);
const apiReport = await apiIntegrator.output("json");
const data = JSON.parse(apiReport);console.log("API Integration Results:", data);
const contentProcessor = new AgentForceAgent({ name: "ContentAnalyzer", tools: ["web_fetch", "filter_content", "fs_read_file", "fs_write_file"]}) .useLLM("openrouter", "qwen/qwen3-235b-a22b-instruct-2507") // Great for content analysis .systemPrompt(` You are a content analysis expert. Extract key information, identify trends, and provide insights. Create structured summaries and actionable recommendations. `) .prompt("Analyze the content trends from these tech blogs and local research files, then create a comprehensive industry trend report");
const trendReport = await contentProcessor.run();
Tools for system operations and development workflows.
const devAutomator = new AgentForceAgent({ name: "DevOpsAssistant", tools: ["os_exec", "fs_read_file", "fs_write_file", "gh_list_repos"]}) .useLLM("openrouter", "mistralai/devstral-medium") // Specialized for dev tasks .systemPrompt(` You are a DevOps automation specialist. Execute system commands safely and efficiently. Monitor build processes and generate reports. Handle git operations and repository management. `) .prompt("Check the current git status, run tests, and create a deployment readiness report");
const deploymentReport = await devAutomator.output("md");console.log(deploymentReport);
const qualityAnalyzer = new AgentForceAgent({ name: "CodeQualityChecker", tools: [ "fs_find_files", "fs_search_content", "os_exec", "fs_write_file" ]}) .useLLM("ollama", "devstral") // Best for code analysis .systemPrompt(` You are a code quality expert. Analyze code patterns, identify issues, and suggest improvements. Run linting tools and generate comprehensive quality reports. `) .prompt("Analyze the TypeScript codebase for code quality issues, run ESLint, and create an improvement plan");
const qualityReport = await qualityAnalyzer.run();
const repoManager = new AgentForceAgent({ name: "RepoManager", tools: ["gh_list_repos", "os_exec", "fs_read_file", "fs_write_file"]}) .useLLM("openrouter", "moonshotai/kimi-k2") // FREE with good tool support .systemPrompt(` You are a repository management specialist. Handle GitHub operations, analyze repository health, and maintain documentation. Provide insights on repository activity and maintenance needs. `) .prompt("List my repositories, analyze their activity, and create a maintenance schedule");
const repoAnalysis = await repoManager.output("json");
MCP (Model Context Protocol) servers provide advanced integrations with external systems and services.
{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "./workspace"], "env": {} }, "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" } }, "sqlite": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-sqlite", "./data/analytics.db"], "env": {} }, "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "${BRAVE_API_KEY}" } } }}
import { AgentForceAgent } from '@agentforce/adk';
const mcpAgent = new AgentForceAgent({ name: "MCPIntegratedAgent", mcps: ["filesystem", "github", "sqlite"], // MCP servers tools: ["fs_write_file", "api_fetch"], // Built-in tools mcpConfig: "./mcp.config.json"}) .useLLM("ollama", "deepseek-r1:7b") // Excellent for complex integrations .systemPrompt(` You are an advanced integration specialist with access to: - File system operations via MCP - GitHub repository access - SQLite database operations - Built-in file and API tools
Use the most appropriate tool for each task. `);
const dynamicAgent = new AgentForceAgent({ name: "DynamicMCPAgent" }) .addMCP("github") // Add GitHub MCP server .addMCP({ // Add custom server name: "analytics-db", command: "python3", args: ["./servers/analytics.py"], env: { DATABASE_URL: process.env.ANALYTICS_DB_URL, API_KEY: process.env.ANALYTICS_API_KEY } }) .useLLM("openrouter", "x-ai/grok-4") // Advanced reasoning for complex tasks .systemPrompt("You have access to GitHub and custom analytics database");
const devWorkflow = new AgentForceAgent({ name: "DevWorkflowAgent", mcps: ["github", "filesystem", "git"], tools: ["fs_write_file"]}) .useLLM("openrouter", "mistralai/devstral-small-1.1") // Optimized for coding .systemPrompt(` You are a senior developer managing code repositories. Use MCP servers for GitHub operations and file management. Create comprehensive development reports and maintain code quality. `) .prompt(` Development workflow task: 1. Check recent commits in the main branch 2. Analyze code changes for potential issues 3. Update project documentation if needed 4. Create a development status report `);
const workflowReport = await devWorkflow.output("md");
const analyticsAgent = new AgentForceAgent({ name: "DataAnalytics", mcps: ["sqlite", "filesystem", "brave-search"], tools: ["api_fetch", "filter_content"]}) .useLLM("openrouter", "qwen/qwen3-235b-a22b-instruct-2507") // Great for data work .systemPrompt(` You are a data analyst with access to: - SQLite database for stored analytics - Web search for market research - File system for report storage - API access for external data sources
Create comprehensive analytics reports with actionable insights. `) .prompt(` Analytics pipeline: 1. Query user engagement data from SQLite 2. Research industry benchmarks via web search 3. Fetch competitor data from external APIs 4. Generate comparative analysis report `);
const analyticsReport = await analyticsAgent.output("json");
const contentManager = new AgentForceAgent({ name: "ContentManager", mcps: ["filesystem", "github"], tools: ["web_fetch", "filter_content", "md_create_ascii_tree"]}) .useLLM("openrouter", "google/gemini-2.5-flash-lite") // Fast content processing .systemPrompt(` You are a content management specialist. Manage documentation, blog posts, and project content. Use GitHub for version control and filesystem for local operations. `) .prompt(` Content management tasks: 1. Audit current documentation structure 2. Identify outdated content 3. Research latest best practices 4. Create content update plan and implement key changes `);
const contentPlan = await contentManager.run();
class IntelligentAgent { private agent: AgentForceAgent;
constructor(name: string) { this.agent = new AgentForceAgent({ name, // Combine built-in tools with MCP servers tools: [ "fs_read_file", "fs_write_file", // File basics "web_fetch", "api_fetch", // Web access "filter_content" // Content processing ], mcps: [ "github", // Advanced git operations "sqlite", // Database access "filesystem" // Advanced file operations ], mcpConfig: "./mcp.config.json" }) .useLLM("ollama", "deepseek-r1:7b") .systemPrompt(` You are an intelligent agent with both built-in tools and MCP server access.
Tool Selection Guidelines: - Use built-in tools for simple, common operations - Use MCP servers for complex, specialized operations - Combine tools when needed for comprehensive solutions
Built-in tools: File I/O, web fetching, content filtering MCP servers: GitHub operations, database queries, advanced file management `); }
async handleTask(task: string, context?: any) { const taskPrompt = context ? `${task}\n\nContext: ${JSON.stringify(context)}` : task;
return await this.agent .prompt(taskPrompt) .output("json"); }
async analyzeProject() { return await this.handleTask(` Project Analysis Task: 1. Get project structure using MCP filesystem server 2. Read key files using built-in fs_read_file 3. Check GitHub repository status using MCP GitHub server 4. Search for TODO/FIXME comments using built-in content tools 5. Create comprehensive project health report `); }
async researchAndImplement(topic: string) { return await this.handleTask(` Research and Implementation: 1. Research "${topic}" using built-in web_fetch 2. Filter and analyze content using built-in tools 3. Check existing implementation in GitHub via MCP 4. Create implementation plan and initial code 5. Save results using appropriate file operations `); }}
// Usageconst smartAgent = new IntelligentAgent("ProjectAssistant");
const projectHealth = await smartAgent.analyzeProject();console.log("Project Health:", JSON.parse(projectHealth));
const implementation = await smartAgent.researchAndImplement("API rate limiting");console.log("Implementation Plan:", JSON.parse(implementation));
class WorkflowOrchestrator { private agents: Map<string, AgentForceAgent> = new Map();
constructor() { // Specialized agents for different tasks this.createAgents(); }
private createAgents() { // File operations specialist this.agents.set("fileOps", new AgentForceAgent({ name: "FileOperationsAgent", tools: ["fs_read_file", "fs_write_file", "fs_list_dir", "fs_search_content"], }) .useLLM("ollama", "devstral") .systemPrompt("You specialize in efficient file operations"));
// MCP integration specialist this.agents.set("mcpOps", new AgentForceAgent({ name: "MCPOperationsAgent", mcps: ["github", "sqlite", "filesystem"], mcpConfig: "./mcp.config.json" }) .useLLM("openrouter", "mistralai/devstral-small-1.1") .systemPrompt("You specialize in MCP server operations"));
// Web operations specialist this.agents.set("webOps", new AgentForceAgent({ name: "WebOperationsAgent", tools: ["web_fetch", "api_fetch", "filter_content"], }) .useLLM("openrouter", "google/gemini-2.5-flash-lite") .systemPrompt("You specialize in web and API operations")); }
async executeWorkflow(workflowType: string, data: any) { switch (workflowType) { case "codeReview": return await this.codeReviewWorkflow(data); case "contentAudit": return await this.contentAuditWorkflow(data); case "dataAnalysis": return await this.dataAnalysisWorkflow(data); default: throw new Error(`Unknown workflow: ${workflowType}`); } }
private async codeReviewWorkflow(repoData: any) { const fileAgent = this.agents.get("fileOps")!; const mcpAgent = this.agents.get("mcpOps")!;
// Step 1: Get repository structure via MCP const repoStructure = await mcpAgent .prompt("Get the repository structure and recent commits") .output("json");
// Step 2: Analyze key files using built-in tools const codeAnalysis = await fileAgent .prompt(`Analyze code quality in key files: ${JSON.stringify(repoStructure)}`) .output("json");
// Step 3: Check GitHub issues and PRs via MCP const githubStatus = await mcpAgent .prompt("Get open issues and pull requests status") .output("json");
return { structure: JSON.parse(repoStructure), analysis: JSON.parse(codeAnalysis), githubStatus: JSON.parse(githubStatus), timestamp: new Date().toISOString() }; }
private async contentAuditWorkflow(siteData: any) { const webAgent = this.agents.get("webOps")!; const fileAgent = this.agents.get("fileOps")!;
// Step 1: Fetch and analyze web content const webContent = await webAgent .prompt(`Audit website content: ${siteData.url}`) .output("json");
// Step 2: Compare with local documentation const localDocs = await fileAgent .prompt("Analyze local documentation structure and content") .output("json");
return { webAudit: JSON.parse(webContent), localDocs: JSON.parse(localDocs), recommendations: "Generated based on comparison", timestamp: new Date().toISOString() }; }
private async dataAnalysisWorkflow(analysisData: any) { const mcpAgent = this.agents.get("mcpOps")!; const webAgent = this.agents.get("webOps")!;
// Step 1: Query database via MCP const dbResults = await mcpAgent .prompt(`Query analytics data: ${JSON.stringify(analysisData)}`) .output("json");
// Step 2: Get external benchmark data const benchmarks = await webAgent .prompt("Research industry benchmarks for comparison") .output("json");
return { data: JSON.parse(dbResults), benchmarks: JSON.parse(benchmarks), analysis: "Comparative analysis results", timestamp: new Date().toISOString() }; }}
// Usageconst orchestrator = new WorkflowOrchestrator();
const codeReview = await orchestrator.executeWorkflow("codeReview", { repo: "my-project"});
const contentAudit = await orchestrator.executeWorkflow("contentAudit", { url: "https://example.com"});
console.log("Code Review Results:", codeReview);console.log("Content Audit Results:", contentAudit);
class RobustToolAgent { private agent: AgentForceAgent; private fallbackStrategies: Map<string, string[]> = new Map();
constructor() { this.agent = new AgentForceAgent({ name: "RobustAgent", tools: ["fs_read_file", "fs_write_file", "web_fetch", "api_fetch"], mcps: ["filesystem", "github"] }) .useLLM("ollama", "deepseek-r1:7b") .debug() // Enable debug logging .systemPrompt(` You are a robust agent that handles errors gracefully. When a tool operation fails, try alternative approaches. Always provide useful information even if some operations fail. `);
// Define fallback strategies this.fallbackStrategies.set("file_read_error", [ "Try reading with different encoding", "Check if file exists first", "Try reading smaller chunks" ]);
this.fallbackStrategies.set("web_fetch_error", [ "Retry with different user agent", "Try alternative URL or endpoint", "Use cached data if available" ]); }
async executeWithRetry(prompt: string, maxRetries: number = 3): Promise<string> { let lastError: Error | null = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) { try { console.log(`Attempt ${attempt}/${maxRetries}`);
const result = await this.agent .prompt(prompt) .output("json");
return result; } catch (error) { lastError = error as Error; console.error(`Attempt ${attempt} failed:`, error.message);
if (attempt < maxRetries) { // Wait before retry with exponential backoff await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000) ); } } }
// If all attempts failed, return error information return JSON.stringify({ error: true, message: `Failed after ${maxRetries} attempts`, lastError: lastError?.message, timestamp: new Date().toISOString(), suggestions: this.getSuggestions(lastError?.message || "") }); }
private getSuggestions(errorMessage: string): string[] { if (errorMessage.includes("file")) { return this.fallbackStrategies.get("file_read_error") || []; } if (errorMessage.includes("fetch") || errorMessage.includes("network")) { return this.fallbackStrategies.get("web_fetch_error") || []; } return ["Check tool configuration", "Verify model supports tools", "Review system prompt"]; }
async validateToolsAvailability(): Promise<object> { try { const validation = await this.agent .prompt(` Test tool availability: 1. Try reading a simple file (like README.md) 2. Test web fetch with a reliable endpoint (like httpbin.org) 3. Verify MCP servers are responding
Return a status report for each tool type. `) .output("json");
return JSON.parse(validation); } catch (error) { return { error: true, message: "Tool validation failed", details: error.message }; } }}
// Usageconst robustAgent = new RobustToolAgent();
// Validate tools firstconst validation = await robustAgent.validateToolsAvailability();console.log("Tool Validation:", validation);
// Execute with retry logicconst result = await robustAgent.executeWithRetry(` Complex task requiring multiple tools: 1. Read project configuration files 2. Fetch external API data 3. Update GitHub repository information 4. Create comprehensive status report`);
console.log("Execution Result:", JSON.parse(result));
class MCPDebugger { static async diagnoseMCPIssues(agent: AgentForceAgent): Promise<object> { try { const diagnosis = await agent .debug() // Enable debug logging .prompt(` Diagnose MCP server connectivity: 1. Test each configured MCP server 2. Verify authentication and permissions 3. Check server response times 4. Report any connection issues
Provide detailed diagnostic information. `) .output("json");
return JSON.parse(diagnosis); } catch (error) { return { mcpDiagnosis: "failed", error: error.message, recommendations: [ "Check MCP server configuration", "Verify environment variables", "Test server connectivity manually", "Review server logs" ] }; } }
static async testMCPServer(serverName: string, config: object): Promise<boolean> { try { const testAgent = new AgentForceAgent({ name: "MCPTester", mcps: [serverName] }) .useLLM("ollama", "deepseek-r1:7b") .debug();
const testResult = await testAgent .prompt(`Test the ${serverName} MCP server with a simple operation`) .output("text");
return testResult.includes("success") || testResult.includes("completed"); } catch (error) { console.error(`MCP server ${serverName} test failed:`, error); return false; } }}
class OptimizedToolAgent { private performanceMetrics: Map<string, number> = new Map();
constructor() { this.initializeMetrics(); }
private initializeMetrics() { // Track average execution times (in ms) this.performanceMetrics.set("fs_read_file", 50); this.performanceMetrics.set("web_fetch", 2000); this.performanceMetrics.set("api_fetch", 1500); this.performanceMetrics.set("mcp_github", 3000); this.performanceMetrics.set("mcp_database", 800); }
selectOptimalTools(requiredCapabilities: string[]): string[] { const toolOptions = { "file_operations": ["fs_read_file", "mcp_filesystem"], "web_data": ["web_fetch", "api_fetch"], "code_management": ["fs_search_content", "mcp_github"], "data_storage": ["fs_write_file", "mcp_database"] };
const selectedTools: string[] = [];
for (const capability of requiredCapabilities) { const options = toolOptions[capability] || [];
// Select fastest tool for the capability const fastest = options.reduce((best, current) => { const bestTime = this.performanceMetrics.get(best) || Infinity; const currentTime = this.performanceMetrics.get(current) || Infinity; return currentTime < bestTime ? current : best; });
if (fastest) selectedTools.push(fastest); }
return selectedTools; }
async createOptimizedAgent(task: string, capabilities: string[]) { const optimalTools = this.selectOptimalTools(capabilities);
const tools = optimalTools.filter(tool => !tool.startsWith("mcp_")); const mcps = optimalTools .filter(tool => tool.startsWith("mcp_")) .map(tool => tool.replace("mcp_", ""));
return new AgentForceAgent({ name: "OptimizedAgent", tools, mcps: mcps.length > 0 ? mcps : undefined }) .useLLM("openrouter", "google/gemini-2.5-flash-lite") // Fast model .systemPrompt(` You are optimized for efficiency. Use the most appropriate tool for each operation. Minimize redundant operations and focus on speed. `) .prompt(task); }}
// Usageconst optimizer = new OptimizedToolAgent();
const fastAgent = await optimizer.createOptimizedAgent( "Quickly analyze project files and create a summary", ["file_operations", "data_storage"]);
const result = await fastAgent.output("json");
🎯 Tool Selection
Built-in First: Use built-in tools for common operations
MCP for Complex: Use MCP servers for specialized integrations
Hybrid Approach: Combine both for comprehensive solutions
⚡ Performance
Fast Models: Use efficient models like gemini-2.5-flash-lite
Parallel Operations: Execute independent operations concurrently
Tool Caching: Cache frequently used tool results
🔒 Security
Environment Variables: Store sensitive data in env vars
Sandboxed Operations: Limit file system access scope
Error Handling: Implement graceful error recovery
🐛 Debugging
Debug Mode: Enable debug logging for troubleshooting
Tool Validation: Test tool availability before use
Error Recovery: Implement fallback strategies
API Reference
Explore detailed tool and MCP APIs → Tools Reference
Basic Examples
See Agent processing in real applications → Basic Examples
You now have comprehensive knowledge of how to effectively use both built-in tools and MCP servers to create powerful, capability-enhanced agents in AgentForce ADK!