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:
| Wrapper | Purpose | Required Env Vars | Optional Env Vars |
|---|---|---|---|
McpAbi() | Smart contract ABI interactions for Ethereum-compatible blockchains | CONTRACT_ABI, CONTRACT_ADDRESS | CONTRACT_NAME, CHAIN_ID, RPC_URL, WALLET_PRIVATE_KEY |
McpAtp() | AI Agent Tokenization Platform - token stats, agent metrics, tokenomics | ATP_WALLET_PRIVATE_KEY, ATP_API_KEY | None |
McpBamm() | Borrow Automated Market Maker operations on Fraxtal | WALLET_PRIVATE_KEY | None |
McpCoinGecko() | Free crypto market data via public API | None | None |
McpCoinGeckoPro() | Premium crypto market data with higher limits | COINGECKO_PRO_API_KEY | None |
McpDiscord() | Discord bot and server management | DISCORD_TOKEN | PATH |
McpFraxlend() | Fraxlend lending platform interactions | WALLET_PRIVATE_KEY | None |
McpIqWiki() | IQ.wiki data access and user activity management | None | None |
McpNearAgent() | NEAR blockchain with AI-driven event processing | ACCOUNT_ID, ACCOUNT_KEY | NEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT |
McpNearIntents() | NEAR Protocol intent swaps functionality | ACCOUNT_ID, ACCOUNT_KEY | NEAR_NETWORK_ID, NEAR_NODE_URL, NEAR_GAS_LIMIT |
McpOdos() | DEX aggregation through ODOS protocol | WALLET_PRIVATE_KEY | None |
McpPolymarket() | Polymarket prediction market interactions | FUNDER_ADDRESS, POLYMARKET_PRIVATE_KEY | None |
McpTelegram() | Telegram bot and channel interactions | TELEGRAM_BOT_TOKEN | None |
McpUpbit() | Upbit cryptocurrency exchange integration | None (public tools) | UPBIT_ACCESS_KEY, UPBIT_SECRET_KEY, UPBIT_ENABLE_TRADING (private tools) |
Third-Party MCP Servers
| Wrapper | Purpose | Required Env Vars | Optional Env Vars |
|---|---|---|---|
McpFilesystem() | File system operations (read/write/list) | None | ALLOWED_DIRECTORIES |
McpGeneric() | Connect to any npm-published MCP server | Depends on server | Depends on server |
McpMemory() | Memory and note-taking capabilities | None | None |
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:
- Import the wrapper function for your MCP server (e.g.,
McpAtp) - Call the function with your configuration (environment variables, options)
- The wrapper returns an
McpToolsetinstance with the connection pre-configured - Call
getTools()to retrieve the available tools - 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):
| Parameter | Type | Required | Description |
|---|---|---|---|
env | object | Varies | Environment variables for the MCP server (see table above). Required for servers that need authentication or configuration, optional for public APIs. |
debug | boolean | No | Enable debug logging (default: false) |
description | string | No | Custom description for the MCP client |
retryOptions.maxRetries | number | No | Maximum retry attempts (default: 2) |
retryOptions.initialDelay | number | No | Initial retry delay in ms (default: 200) |
samplingHandler | SamplingHandler | No | Handler 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 serversetSamplingHandler(handler)- Set LLM sampling handlerremoveSamplingHandler()- Remove sampling handlerrefreshTools(context?)- Clear cache and fetch tools againclose()- 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
| Mode | Use Case | Configuration |
|---|---|---|
| Stdio | Local MCP servers running as processes | mode: "stdio" with command/args |
| SSE | Remote MCP servers over HTTP | mode: "sse" with serverUrl |
Configuration Parameters
McpConfig Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Display name for the MCP client |
description | string | Yes | Description of the client's purpose |
transport | McpTransportType | Yes | Connection configuration (stdio or SSE) |
timeout | number | No | Request timeout in milliseconds |
retryOptions.maxRetries | number | No | Maximum number of retries for failed requests |
retryOptions.initialDelay | number | No | Initial delay before retry in milliseconds |
retryOptions.maxDelay | number | No | Maximum delay between retries in milliseconds |
headers | Record | No | Custom headers for requests |
cacheConfig.enabled | boolean | No | Whether to cache tools (default: true) |
cacheConfig.maxAge | number | No | Maximum age of cached tools in milliseconds |
cacheConfig.maxSize | number | No | Maximum number of tools to cache |
debug | boolean | No | Enable debug logging |
samplingHandler | SamplingHandler | No | Handler for MCP sampling requests (allows MCP servers to use LLM) |
McpToolset Constructor
new McpToolset(config: McpConfig, toolFilter?: string[] | Function)| Parameter | Type | Required | Description |
|---|---|---|---|
config | McpConfig | Yes | Configuration object (see table above) |
toolFilter | string[] | Function | No | Filter 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 devExample 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
- Check the MCP Starter Template for complete examples
- See MCP Integration Examples for advanced patterns
- Visit FastMCP Documentation for detailed FastMCP usage
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
McpErrortypes (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
McpToolsetfor custom servers (more control).
Troubleshooting
| Issue | Cause | Solution |
|---|---|---|
| Connection timeout | MCP server not running or slow startup | Check server is running, increase timeout in McpConfig |
| Tool not available | Tool name doesn't match or filtering excluded it | Verify tool name with getTools(), check tool_filter parameter |
| "npx: command not found" | Node.js/npm not installed or not in PATH | Install Node.js, ensure npm/npx in your $PATH, set env.PATH |
| Memory leaks | Connection not closed properly | Always use try/finally block, call toolset.close() |
| Parameter mismatch | Tool args don't match schema | Check McpConfig transport matches server requirements, review tool schema |
| Authentication fails | Wrong credentials or missing env vars | Verify API keys, check environment variable names match exactly |
Related Topics
How is this guide?