TypeScriptADK-TS
Tools

MCP Tools

Model Context Protocol tools for standardized integrations

Model Context Protocol (Mcp) tools provide standardized interfaces for connecting LLMs with external applications, data sources, and services. ADK TypeScript supports both consuming Mcp servers and exposing ADK tools as Mcp servers.

What is Model Context Protocol?

Mcp is an open standard that standardizes how Large Language Models communicate with external systems. It acts as a universal connection mechanism that simplifies context sharing, action execution, and system interaction.

Key Components

  • Data Sources: Access to external resources and content
  • Interactive Templates: Dynamic prompts and conversation patterns
  • Actionable Functions: Tools and operations for system interaction
  • Client-Server Architecture: Standardized communication patterns

Universal Standard

Mcp enables any LLM to work with any Mcp-compatible service, creating a universal ecosystem of AI-enabled tools and data sources.

Integration Patterns

ADK TypeScript supports two primary Mcp integration patterns:

🔌 Mcp Client

Use existing Mcp servers within ADK agents

🖥️ Mcp Server

Expose ADK tools via Mcp server for other clients

ADK as Mcp Client

Connect your ADK agents to existing Mcp servers to leverage external tools and data sources.

Integration Options

ADK TypeScript provides two ways to integrate with MCP servers:

  1. Wrapper Functions (Recommended) - Use dedicated functions like McpAtp(), McpNearAgent() for IQAI servers
  2. McpToolset Class (For Unsupported Servers) - Direct McpToolset usage for any MCP server

McpToolset Class

The McpToolset class serves as the bridge between ADK agents and Mcp servers:

  • Connection Management: Establish connections to local or remote Mcp servers
  • Tool Discovery: Query servers for available tools and capabilities
  • Schema Adaptation: Convert Mcp schemas to ADK-compatible tools
  • Call Proxying: Forward tool calls to Mcp servers and return results
  • Lifecycle Management: Handle connection cleanup and resource management

For supported IQAI MCP servers, use the convenient wrapper functions:

import { McpAtp, AgentBuilder } from "@iqai/adk";

// Create ATP toolset with wrapper function
const toolset = McpAtp({
  env: {
    ATP_WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
    ATP_API_KEY: process.env.ATP_API_KEY,
  },
  debug: process.env.NODE_ENV === "development",
  retryOptions: {
    maxRetries: 2,
    initialDelay: 200,
  },
});

// Get available tools
const mcpTools = await toolset.getTools();

// Create agent with MCP tools using AgentBuilder
const { runner } = await AgentBuilder.create("blockchain_agent")
  .withModel("gemini-2.5-flash")
  .withDescription("Agent for blockchain and DeFi operations")
  .withTools(...mcpTools)
  .build();

// Use the agent
const response = await runner.ask("Get ATP statistics for token 0x123...");

// Clean up when done
await toolset.close();

Using McpToolset (For Unsupported Servers)

When we don't have a wrapper function for a specific MCP server, use the McpToolset class:

import { McpToolset, AgentBuilder, type McpConfig } from "@iqai/adk";

// Configure MCP connection for unsupported server
const mcpConfig: McpConfig = {
  name: "Filesystem MCP Client",
  description: "Client for filesystem operations",
  debug: process.env.NODE_ENV === "development",
  retryOptions: {
    maxRetries: 3,
    initialDelay: 200,
  },
  cacheConfig: {
    enabled: true,
  },
  transport: {
    mode: "stdio",
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/directory"],
    env: {
      PATH: process.env.PATH || "",
    },
  },
};

// Initialize MCP toolset
const mcpToolset = new McpToolset(mcpConfig);

// Discover available tools
const mcpTools = await mcpToolset.getTools();
console.log(`Found ${mcpTools.length} MCP tools`);

// Create agent with MCP tools using AgentBuilder
const { runner } = await AgentBuilder.create("filesystem_agent")
  .withModel("gemini-2.5-flash")
  .withDescription("An agent that can perform filesystem operations")
  .withInstruction("You can read, write, and manage files using MCP tools.")
  .withTools(...mcpTools)
  .build();

// Use the agent
const response = await runner.ask("List all .ts files in the src directory");

// Clean up when done
await mcpToolset.close();

IQAI MCP Servers Integration

IQAI provides specialized MCP servers for blockchain and AI operations:

import { McpToolset, AgentBuilder } from "@iqai/adk";

// Connect to IQAI ATP server
const atpToolset = new McpToolset({
  name: "ATP MCP Client",
  description: "Client for AI Agent Tokenization Platform",
  transport: {
    mode: "stdio",
    command: "pnpm",
    args: ["dlx", "@iqai/mcp-atp"],
    env: {
      WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
      ATP_API_KEY: process.env.ATP_API_KEY,
      PATH: process.env.PATH || "",
    },
  },
});

// Get ATP tools
const atpTools = await atpToolset.getTools();

// Create specialized blockchain agent using AgentBuilder
const { runner } = await AgentBuilder.create("blockchain_agent")
  .withModel("gemini-2.5-flash")
  .withDescription("Agent for blockchain and DeFi operations")
  .withInstruction("You can interact with blockchain protocols, manage tokens, and access DeFi platforms.")
  .withTools(...atpTools)
  .build();

// Example usage
const stats = await runner.ask("Get statistics for agent token 0x123...");

Multiple MCP Servers

You can connect to multiple IQAI MCP servers simultaneously:

import { McpAtp, McpFraxlend, McpNearAgent, AgentBuilder } from "@iqai/adk";

// Connect to multiple servers with wrapper functions
const atpToolset = McpAtp({
  env: {
    ATP_WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
    ATP_API_KEY: process.env.ATP_API_KEY,
  },
});

const fraxlendToolset = McpFraxlend({
  env: {
    WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
  },
});

const nearToolset = McpNearAgent({
  env: {
    ACCOUNT_ID: process.env.NEAR_ACCOUNT_ID,
    ACCOUNT_KEY: process.env.NEAR_ACCOUNT_KEY,
    NEAR_NETWORK_ID: "testnet",
  },
});

// Combine tools from multiple servers
const atpTools = await atpToolset.getTools();
const fraxlendTools = await fraxlendToolset.getTools();
const nearTools = await nearToolset.getTools();
const allTools = [...atpTools, ...fraxlendTools, ...nearTools];

// Create agent with combined tools
const { runner } = await AgentBuilder.create("multi_mcp_assistant")
  .withModel("gemini-2.5-flash")
  .withDescription("An assistant with multiple MCP server capabilities")
  .withTools(...allTools)
  .build();

Mixed Approach (Wrappers + McpToolset)

You can also combine wrapper functions with McpToolset for unsupported servers:

import { McpAtp, McpToolset, AgentBuilder } from "@iqai/adk";

// Use wrapper for supported server
const atpToolset = McpAtp({
  env: {
    ATP_WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
    ATP_API_KEY: process.env.ATP_API_KEY,
  },
});

// Use McpToolset for unsupported server
const customToolset = new McpToolset({
  name: "Custom Client",
  transport: {
    mode: "stdio",
    command: "pnpm",
    args: ["dlx", "@custom/mcp-server"],
    env: {
      CUSTOM_API_KEY: process.env.CUSTOM_API_KEY,
    },
  },
});

// Combine tools from both approaches
const atpTools = await atpToolset.getTools();
const customTools = await customToolset.getTools();
const allTools = [...atpTools, ...customTools];

// Create agent with combined tools
const { runner } = await AgentBuilder.create("mixed_mcp_assistant")
  .withModel("gemini-2.5-flash")
  .withDescription("An assistant with mixed MCP server capabilities")
  .withTools(...allTools)
  .build();

Resource Cleanup

Always clean up MCP resources when done:

try {
  // Use your agent and tools
  const response = await runner.ask("Get ATP statistics for contract 0x123...");
} finally {
  // Clean up resources
  await toolset.close();
}

Integration with ADK TypeScript

All IQAI MCP servers are designed to work seamlessly with:

  • Wrapper functions like McpAtp(), McpNearAgent(), etc. for supported servers
  • McpToolset class for connecting to any MCP server when no wrapper is available

Both approaches provide:

  • Automatic tool discovery and registration
  • Type-safe tool usage
  • Error handling and retry logic
  • Resource management and cleanup

Connection Types

🔧 Stdio Connection

Connect to local MCP servers via standard input/output

🌐 SSE Connection

Connect to remote MCP servers via Server-Sent Events

Stdio Connection Example

Most MCP servers use stdio transport for local connections:

const mcpConfig: McpConfig = {
  name: "Local MCP Server",
  transport: {
    mode: "stdio",
    command: "node", // or "python", "pnpm", etc.
    args: ["path/to/server.js"],
    env: {
      // Server-specific environment variables
      API_KEY: process.env.API_KEY,
      PATH: process.env.PATH || "",
    },
  },
};

SSE Connection Example

For remote MCP servers accessible via HTTP:

const mcpConfig: McpConfig = {
  name: "Remote MCP Server",
  transport: {
    mode: "sse",
    url: "https://api.example.com/mcp",
    headers: {
      Authorization: `Bearer ${process.env.API_TOKEN}`,
    },
  },
};

Common MCP Servers

Popular MCP servers you can integrate with:

  • Filesystem Server: File operations and management
  • Database Server: SQL database queries and operations
  • Web Search Server: Internet search capabilities
  • Git Server: Version control operations
  • API Servers: Various third-party service integrations

Integration Process

  1. Server Setup: Install and configure the MCP server
  2. Connection Configuration: Define connection parameters (stdio or SSE)
  3. Toolset Creation: Initialize toolset using wrapper functions or McpToolset
  4. Tool Registration: Add MCP tools to your agent's tool list using AgentBuilder
  5. Agent Execution: Use tools automatically based on agent logic via runner
  6. Cleanup Management: Properly close connections and clean up resources

Error Handling

import { McpError } from "@iqai/adk";

try {
  const toolset = new McpToolset(mcpConfig);
  const tools = await toolset.getTools();
  // Use tools...
} catch (error) {
  if (error instanceof McpError) {
    console.error(`MCP Error (${error.type}): ${error.message}`);
    if (error.originalError) {
      console.error("Original error:", error.originalError);
    }
  } else {
    console.error("Unexpected error:", error);
  }
} finally {
  await toolset?.close();
}

ADK as MCP Server

Expose your ADK tools and agents as MCP servers for consumption by other MCP clients.

Server Architecture

Transform ADK components into MCP-compatible services:

  • Tool Exposure: Make custom tools available via MCP protocol
  • Agent Services: Expose agent capabilities as MCP functions
  • Resource Sharing: Provide access to data and content through MCP
  • Standard Compliance: Follow MCP specifications for compatibility

Benefits

  • Universal Access: Make tools available to any MCP client
  • Ecosystem Integration: Join the broader MCP ecosystem
  • Reusability: Share functionality across different applications
  • Standardization: Use established protocols for tool sharing

Implementation Considerations

  • Protocol Compliance: Ensure full MCP specification compliance
  • Security: Implement proper authentication and authorization
  • Performance: Optimize for network communication overhead
  • Documentation: Provide clear tool descriptions and usage patterns

Connection Management

Local Connections (Stdio)

For local MCP servers running as separate processes:

  • Process Management: Handle server process lifecycle
  • Communication: Use stdin/stdout for bidirectional communication
  • Error Handling: Manage process failures and restarts
  • Resource Cleanup: Properly terminate server processes

Remote Connections (SSE)

For remote MCP servers accessed over network:

  • Network Communication: Handle HTTP/SSE connections
  • Authentication: Manage API keys and credentials
  • Retry Logic: Implement connection recovery and retries
  • Load Balancing: Distribute requests across multiple servers

Tool Discovery and Adaptation

Discovery Process

  1. Connection Establishment: Connect to MCP server
  2. Capability Query: Request available tools and resources
  3. Schema Retrieval: Get tool definitions and parameters
  4. Validation: Verify tool compatibility and requirements

Schema Adaptation

MCP tool schemas are automatically converted to ADK-compatible formats:

  • Parameter Mapping: Convert MCP parameters to TypeScript types
  • Return Type Handling: Adapt MCP responses to ADK expectations
  • Error Translation: Map MCP errors to ADK error patterns
  • Documentation Integration: Include MCP descriptions in tool metadata

Security and Authentication

Client Security

When consuming MCP servers:

  • Server Validation: Verify server identity and trustworthiness
  • Communication Security: Use secure connection methods
  • Access Controls: Implement proper permission checks
  • Data Privacy: Protect sensitive data in transit

Server Security

When exposing MCP servers:

  • Client Authentication: Verify client identity and permissions
  • API Rate Limiting: Prevent abuse and overuse
  • Data Sanitization: Validate and sanitize all inputs
  • Audit Logging: Track access and usage patterns

Performance Considerations

Optimization Strategies

  • Connection Pooling: Reuse connections for multiple operations
  • Caching: Cache tool definitions and frequent responses
  • Async Operations: Use non-blocking communication patterns
  • Batch Processing: Group multiple operations when possible

Monitoring and Debugging

  • Connection Health: Monitor server connectivity and responsiveness
  • Performance Metrics: Track latency and throughput
  • Error Rates: Monitor failure rates and error patterns
  • Debug Logging: Detailed logging for troubleshooting

Best Practices

Development

Connection Management

Always properly close MCP connections and clean up resources to prevent memory leaks and zombie processes.

  • Error Handling: Implement robust error handling and recovery
  • Resource Management: Properly manage connections and cleanup
  • Testing: Test with various MCP servers and scenarios
  • Documentation: Document tool usage and requirements clearly

Production Deployment

  • Health Checks: Monitor MCP server availability
  • Failover Strategies: Implement backup servers and fallback options
  • Scalability: Design for horizontal scaling and load distribution
  • Monitoring: Comprehensive logging and metrics collection

Tool Design

  • Clear Interfaces: Design intuitive tool parameters and responses
  • Comprehensive Documentation: Provide detailed usage instructions
  • Error Messages: Return actionable error information
  • Version Management: Handle API versioning and compatibility

Common Use Cases

Data Integration

  • Database Access: Query databases through MCP database servers
  • File Operations: Manage files using filesystem MCP servers
  • API Access: Connect to web services via MCP API gateways
  • Content Management: Access CMS systems through MCP interfaces

Workflow Automation

  • Process Orchestration: Chain MCP tools for complex workflows
  • Event Handling: Respond to external events via MCP servers
  • Data Processing: Transform data using specialized MCP tools
  • Integration Patterns: Connect multiple systems through MCP

How is this guide?