Skip to content

Tools & MCP Usage


Tool Integration MCP Protocol Advanced Features

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);

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

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);

MCP (Model Context Protocol) servers provide advanced integrations with external systems and services.

mcp.config.json
{
"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}"
}
}
}
}
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");
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
`);
}
}
// Usage
const 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()
};
}
}
// Usage
const 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
};
}
}
}
// Usage
const robustAgent = new RobustToolAgent();
// Validate tools first
const validation = await robustAgent.validateToolsAvailability();
console.log("Tool Validation:", validation);
// Execute with retry logic
const 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);
}
}
// Usage
const 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

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!