TypeScriptADK-TS

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. Simplified Wrapper Functions (Recommended) - Use dedicated functions like McpAtp(), McpNearAgent() for IQAI servers
  2. McpToolset Class (Legacy) - 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 IQAI MCP servers, use the simplified wrapper functions:

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

// Create ATP toolset with simplified syntax
const atpToolset = 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",
});

// Get tools and create agent
const atpTools = await atpToolset.getTools();
const agent = new LlmAgent({
  name: "blockchain_agent",
  model: "gemini-2.5-flash",
  description: "Agent for blockchain and DeFi operations",
  tools: atpTools,
});

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

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

Legacy Integration (McpToolset)

Here's how to integrate Mcp servers using the traditional approach:

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

// Configure Mcp connection
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
const agent = new LlmAgent({
  name: "filesystem_agent",
  model: "gemini-2.5-flash",
  description: "An agent that can perform filesystem operations",
  instruction: "You can read, write, and manage files using Mcp tools.",
  tools: mcpTools,
});

// Use the agent
const response = await agent.run("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, LlmAgent } 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
const blockchainAgent = new LlmAgent({
  name: "blockchain_agent",
  model: "gemini-2.5-flash",
  description: "Agent for blockchain and DeFi operations",
  instruction: "You can interact with blockchain protocols, manage tokens, and access DeFi platforms.",
  tools: atpTools,
});

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

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 MCPToolset with connection details
  4. Tool Registration: Add MCP tools to your agent's tool list
  5. Agent Execution: Use tools automatically based on agent logic
  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