TypeScriptADK-TS

MCP Tools

Connect to external systems using the Model Context Protocol standard

Model Context Protocol (MCP) is an open standard for connecting AI agents with external systems, data sources, and services. ADK-TS provides seamless MCP integration, allowing you to consume MCP servers in your agents or expose your ADK-TS tools as MCP servers.

Quick Start

Use wrapper functions to connect to MCP servers with minimal configuration:

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

// Initialize ATP MCP toolset
const atpToolset = McpAtp({
  env: {
    ATP_WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
    ATP_API_KEY: process.env.ATP_API_KEY,
  },
});

// Get tools and create agent
const tools = await atpToolset.getTools();

const agent = new LlmAgent({
  name: "blockchain_agent",
  model: "gemini-2.5-flash",
  description:
    "An agent that queries blockchain data and interacts with DeFi protocols",
  instruction: "Query blockchain data and interact with DeFi protocols",
  tools,
});

// Always cleanup when done
await atpToolset.close();

Available MCP Servers

ADK-TS provides wrapper functions for IQ AI's MCP servers and popular third-party servers. These wrappers simplify configuration and handle connection details automatically.

IQ AI MCP Servers

IQ AI provides specialized MCP servers for blockchain, DeFi, and AI operations:

WrapperPurposeRequired Env VarsOptional Env Vars
McpAbi()Smart contract ABI interactions for Ethereum-compatible blockchainsCONTRACT_ABI, CONTRACT_ADDRESSCONTRACT_NAME, CHAIN_ID, RPC_URL, WALLET_PRIVATE_KEY
McpAtp()AI Agent Tokenization Platform - token stats, agent metrics, tokenomicsATP_WALLET_PRIVATE_KEY, ATP_API_KEYNone
McpBamm()Borrow Automated Market Maker operations on FraxtalWALLET_PRIVATE_KEYNone
McpCoinGecko()Free crypto market data via public APINoneNone
McpCoinGeckoPro()Premium crypto market data with higher limitsCOINGECKO_PRO_API_KEYNone
McpDiscord()Discord bot and server managementDISCORD_TOKENPATH
McpFraxlend()Fraxlend lending platform interactionsWALLET_PRIVATE_KEYNone
McpIqWiki()IQ.wiki data access and user activity managementNoneNone
McpNearAgent()NEAR blockchain with AI-driven event processingACCOUNT_ID, ACCOUNT_KEYNEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT
McpNearIntents()NEAR Protocol intent swaps functionalityACCOUNT_ID, ACCOUNT_KEYNEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT
McpOdos()DEX aggregation through ODOS protocolWALLET_PRIVATE_KEYNone
McpPolymarket()Polymarket prediction market interactionsFUNDER_ADDRESS, POLYMARKET_PRIVATE_KEYNone
McpTelegram()Telegram bot and channel interactionsTELEGRAM_BOT_TOKENNone
McpUpbit()Upbit cryptocurrency exchange integrationNone (public tools)UPBIT_ACCESS_KEY, UPBIT_SECRET_KEY, UPBIT_ENABLE_TRADING (private tools)

Third-Party MCP Servers

WrapperPurposeRequired Env VarsOptional Env Vars
McpFilesystem()File system operations (read/write/list)NoneALLOWED_DIRECTORIES
McpGeneric()Connect to any npm-published MCP serverDepends on serverDepends on server
McpMemory()Memory and note-taking capabilitiesNoneNone

Using Wrapper Functions

Wrapper functions are pre-configured factory functions that create McpToolset instances for specific MCP servers. Instead of manually configuring connection details, you import a wrapper function (like McpAtp, McpCoinGecko, etc.) and call it with your configuration. The wrapper handles all the underlying MCP connection setup.

How it works:

  1. Import the wrapper function for your MCP server (e.g., McpAtp)
  2. Call the function with your configuration (environment variables, options)
  3. The wrapper returns an McpToolset instance with the connection pre-configured
  4. Call getTools() to retrieve the available tools
  5. Add the tools to your agent

Single MCP Server

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

const atpToolset = McpAtp({
  env: {
    ATP_WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
    ATP_API_KEY: process.env.ATP_API_KEY,
  },
});

const tools = await atpToolset.getTools();

const blockchainAgent = new LlmAgent({
  name: "blockchain_agent",
  model: "gemini-2.5-flash",
  description:
    "An agent that queries agent tokenomics and ATP platform statistics",
  instruction: "Query agent tokenomics and ATP platform statistics",
  tools,
});

await atpToolset.close();

Multiple MCP Servers

Combine tools from multiple MCP servers for comprehensive functionality:

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

// Initialize multiple toolsets
const atpToolset = McpAtp({
  env: {
    ATP_WALLET_PRIVATE_KEY: process.env.WALLET_PRIVATE_KEY,
    ATP_API_KEY: process.env.ATP_API_KEY,
  },
});

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

const cryptoToolset = McpCoinGecko();

// Get all tools in parallel
const [atpTools, nearTools, cryptoTools] = await Promise.all([
  atpToolset.getTools(),
  nearToolset.getTools(),
  cryptoToolset.getTools(),
]);

// Create agent with combined tools
const defiAssistantAgent = new LlmAgent({
  name: "defi_assistant_agent",
  model: "gemini-2.5-flash",
  description:
    "A comprehensive DeFi assistant with access to multiple blockchain and market data sources",
  instruction: `You have access to:
    - ATP tools for agent tokenomics and statistics
    - NEAR Protocol tools for blockchain operations
    - CoinGecko for real-time crypto market data
    Use these tools to provide comprehensive DeFi insights`,
  tools: [...atpTools, ...nearTools, ...cryptoTools],
});

// Always cleanup all connections
await Promise.all([
  atpToolset.close(),
  nearToolset.close(),
  cryptoToolset.close(),
]);

Wrapper Configuration Options

All wrapper functions accept a configuration object. Only env is typically required (for servers that need credentials):

ParameterTypeRequiredDescription
envobjectVariesEnvironment variables for the MCP server (see table above). Required for servers that need authentication or configuration, optional for public APIs.
debugbooleanNoEnable debug logging (default: false)
descriptionstringNoCustom description for the MCP client
retryOptions.maxRetriesnumberNoMaximum retry attempts (default: 2)
retryOptions.initialDelaynumberNoInitial retry delay in ms (default: 200)
samplingHandlerSamplingHandlerNoHandler for MCP sampling requests (advanced use)

McpToolset Methods

Both wrapper functions and direct McpToolset usage return McpToolset instances with the following methods:

  • getTools(context?) - Retrieve tools from MCP server
  • setSamplingHandler(handler) - Set LLM sampling handler
  • removeSamplingHandler() - Remove sampling handler
  • refreshTools(context?) - Clear cache and fetch tools again
  • close() - Close connection and cleanup resources

Using McpToolset for Custom Servers

For custom MCP servers not covered by wrapper functions, use McpToolset directly to connect to and consume MCP servers. This provides full control over connection configuration, tool discovery, and filtering.

Note: This is for connecting TO existing MCP servers, not for creating them. See "Exposing ADK-TS Tools as MCP Server" below for creating servers.

Connection Types

ModeUse CaseConfiguration
StdioLocal MCP servers running as processesmode: "stdio" with command/args
SSERemote MCP servers over HTTPmode: "sse" with serverUrl

Configuration Parameters

McpConfig Parameters

ParameterTypeRequiredDescription
namestringYesDisplay name for the MCP client
descriptionstringYesDescription of the client's purpose
transportMcpTransportTypeYesConnection configuration (stdio or SSE)
timeoutnumberNoRequest timeout in milliseconds
retryOptions.maxRetriesnumberNoMaximum number of retries for failed requests
retryOptions.initialDelaynumberNoInitial delay before retry in milliseconds
retryOptions.maxDelaynumberNoMaximum delay between retries in milliseconds
headersRecordNoCustom headers for requests
cacheConfig.enabledbooleanNoWhether to cache tools (default: true)
cacheConfig.maxAgenumberNoMaximum age of cached tools in milliseconds
cacheConfig.maxSizenumberNoMaximum number of tools to cache
debugbooleanNoEnable debug logging
samplingHandlerSamplingHandlerNoHandler for MCP sampling requests (allows MCP servers to use LLM)

McpToolset Constructor

new McpToolset(config: McpConfig, toolFilter?: string[] | Function)
ParameterTypeRequiredDescription
configMcpConfigYesConfiguration object (see table above)
toolFilterstring[] | FunctionNoFilter tools by name array or custom function (tool, context?) => boolean

Stdio Connection (Local Server)

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

const mcpConfig: McpConfig = {
  name: "Filesystem MCP",
  description: "Local file system operations",
  transport: {
    mode: "stdio",
    command: "npx",
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
    env: { PATH: process.env.PATH || "" },
  },
};

const toolset = new McpToolset(mcpConfig);
const tools = await toolset.getTools();

const fileAgent = new LlmAgent({
  name: "file_agent",
  model: "gemini-2.5-flash",
  description: "An agent that manages file operations in allowed directories",
  instruction:
    "Manage files in the allowed directory. Always ask before modifying files",
  tools,
});

await toolset.close();

SSE Connection (Remote Server)

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

const remoteConfig: McpConfig = {
  name: "Remote API Server",
  description: "Remote MCP server",
  transport: {
    mode: "sse",
    serverUrl: "https://mcp-api.example.com/v1/mcp",
    headers: {
      Authorization: `Bearer ${process.env.MCP_AUTH_TOKEN}`,
    },
  },
};

const toolset = new McpToolset(remoteConfig);
const tools = await toolset.getTools();

const apiAgent = new LlmAgent({
  name: "api_agent",
  model: "gemini-2.5-flash",
  description: "An agent that interacts with remote API endpoints",
  tools,
});

await toolset.close();

McpToolset vs Wrapper Functions

Use Wrapper Functions when:

  • Connecting to IQ AI's pre-built services (ATP, NEAR, Fraxlend, etc.)
  • You want automatic configuration and connection management
  • Configuration is simple (mostly environment variables)

Use McpToolset when:

  • Connecting to custom or community MCP servers
  • You need fine-grained control over timeouts, retries, and caching
  • Working with remote endpoints requiring custom headers
  • Building custom tool filtering or schema adaptation

Creating MCP Servers with ADK-TS

You can create your own MCP servers to expose custom tools and functionality to any MCP client (including ADK agents, Claude Desktop, etc.). ADK provides a starter template using FastMCP for building MCP servers quickly.

Quick Start

Create a new MCP server project using the ADK CLI:

# Install the ADK CLI globally
npm install -g @iqai/adk-cli

# Create a new MCP server project using the starter template
adk new --template mcp-starter my-mcp-server

# Navigate to the project directory
cd my-mcp-server

# Install dependencies
pnpm install

# Start the development server (in a separate terminal)
pnpm dev

Example MCP Server

Here's a simple weather MCP server structure:

// src/index.ts
import { FastMCP } from "fastmcp";
import { weatherTool } from "./tools/weather.js";

async function main() {
  const server = new FastMCP({
    name: "Weather MCP Server",
    version: "1.0.0",
  });

  server.addTool(weatherTool);

  await server.start({
    transportType: "stdio",
  });
}

main().catch(console.error);
// src/tools/weather.ts
import { z } from "zod";

export const weatherTool = {
  name: "get_weather",
  description: "Get current weather for a city",
  parameters: z.object({
    city: z.string().describe("City name"),
  }),
  execute: async ({ city }: { city: string }) => {
    // Your weather API logic here
    return { temperature: 72, condition: "Sunny" };
  },
};

Using Your MCP Server with ADK Agents

Once created, connect to your custom MCP server from an ADK agent:

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

const customToolset = new McpToolset({
  name: "My Custom Server",
  description: "Custom MCP server with weather tools",
  transport: {
    mode: "stdio",
    command: "node",
    args: ["./my-mcp-server/dist/index.js"],
  },
});

const tools = await customToolset.getTools();

const agent = new LlmAgent({
  name: "weather_agent",
  model: "gemini-2.5-flash",
  description: "An agent with access to custom weather tools",
  tools,
});

Learn More

Best Practices

To effectively use MCP tools in your agents:

  • Always Close Connections: Use try/finally blocks to ensure toolset.close() is called, even when errors occur. Unclosed connections cause memory leaks and zombie processes.
  • Filter Tools When Needed: Load only the tools your agent needs using the tool filter parameter. This improves performance and reduces LLM confusion.
  • Handle Errors Gracefully: Check for McpError types (CONNECTION_ERROR, TIMEOUT_ERROR) and provide appropriate fallbacks or error messages.
  • Use Environment-Specific Configuration: Use shorter timeouts and fewer retries in development, longer timeouts and more retries in production.
  • Verify Environment Variables: Double-check that all required environment variables are set correctly before initializing MCP connections.
  • Choose the Right Approach: Use wrapper functions for IQ AI servers (simpler), use McpToolset for custom servers (more control).

Troubleshooting

IssueCauseSolution
Connection timeoutMCP server not running or slow startupCheck server is running, increase timeout in McpConfig
Tool not availableTool name doesn't match or filtering excluded itVerify tool name with getTools(), check tool_filter parameter
"npx: command not found"Node.js/npm not installed or not in PATHInstall Node.js, ensure npm/npx in your $PATH, set env.PATH
Memory leaksConnection not closed properlyAlways use try/finally block, call toolset.close()
Parameter mismatchTool args don't match schemaCheck McpConfig transport matches server requirements, review tool schema
Authentication failsWrong credentials or missing env varsVerify API keys, check environment variable names match exactly

How is this guide?