MCP Tools
Connect to any MCP server - built-in, external, or custom
The Model Context Protocol (MCP) is an open standard for connecting AI agents with external systems, data sources, and services. ADK-TS provides comprehensive MCP support, allowing you to:
- Use IQ AI's built-in MCP servers with convenient wrapper functions
- Integrate any external MCP server from the ecosystem (Anthropic's official servers, community servers, etc.)
- Create and deploy your own custom MCP servers using our FastMCP template
- Expose your ADK-TS tools as MCP servers for other applications to consume
Universal MCP Compatibility
ADK-TS can connect to any MCP-compliant server. If it follows the MCP specification, ADK-TS can use it - whether it's from IQ AI, Anthropic, the community, or custom-built.
Quick Start
Option 1: Using IQ AI's Built-in MCP Servers
Use wrapper functions for IQ AI's pre-built 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();Option 2: Using External MCP Servers
Connect to any external MCP server (Anthropic's official servers, community servers, etc.) using McpToolset:
import { McpToolset, LlmAgent } from "@iqai/adk";
// Connect to Anthropic's filesystem server
const filesystemToolset = new McpToolset({
name: "Filesystem MCP",
description: "Local file system operations",
transport: {
mode: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"],
env: {
PATH: process.env.PATH || "",
},
},
});
const tools = await filesystemToolset.getTools();
const agent = new LlmAgent({
name: "file_manager",
model: "gemini-2.5-flash",
description: "An agent that manages files and directories",
instruction: "Help users with file operations",
tools,
});
await filesystemToolset.close();Available MCP Servers
IQ AI's Built-in MCP Servers
IQ AI provides wrapper functions for specialized MCP servers covering blockchain, DeFi, messaging, and AI operations. These wrappers simplify configuration and handle connection details automatically.
Available Servers (constantly expanding):
- Blockchain & DeFi:
McpAtp(),McpBamm(),McpFraxlend(),McpOdos(),McpNearAgent(),McpNearIntents(),McpAbi() - Market Data:
McpCoinGecko(),McpCoinGeckoPro(),McpDefiLlama(),McpDeBank(),McpUpbit() - Prediction Markets:
McpPolymarket(),McpKalshi(),McpLimitless(),McpOpinion() - Messaging & Social:
McpDiscord(),McpTelegram() - Information:
McpIqWiki()
External MCP Servers
ADK-TS can connect to any MCP-compliant server using McpToolset. Popular external MCP servers include:
Anthropic's Official MCP Servers:
- Filesystem - Read, write, and search local files
- Brave Search - Web search via Brave Search API
- GitHub - Repository operations and management
- PostgreSQL - Database queries and operations
- Google Maps - Location services and directions
- Slack - Workspace integration
Community MCP Servers:
- E2B Code Interpreter
- Obsidian
- Linear
- Sentry
Browse more community servers →
Third-Party Wrappers in ADK-TS
ADK-TS also includes convenience wrappers for popular third-party MCP servers:
McpFilesystem()- File system operations (read/write/list)McpMemory()- Memory and note-taking capabilities
Any MCP Server Works
Don't see a wrapper for the MCP server you want to use? No problem! Use McpToolset directly to connect to any MCP-compliant server, whether it's from Anthropic, the community, or custom-built.
Using Wrapper Functions
Wrapper functions are pre-configured factory functions that create McpToolset instances for specific MCP servers. They're available for IQ AI's built-in servers and some popular third-party servers.
How wrapper functions work:
- 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 (both built-in and external) for comprehensive functionality:
import {
McpAtp,
McpNearAgent,
McpCoinGecko,
McpToolset,
LlmAgent,
} from "@iqai/adk";
// IQ AI's built-in servers
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();
// External server (Anthropic's Brave Search)
const braveSearchToolset = new McpToolset({
name: "Brave Search",
description: "Web search via Brave",
transport: {
mode: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-brave-search"],
env: {
BRAVE_API_KEY: process.env.BRAVE_API_KEY!,
PATH: process.env.PATH || "",
},
},
});
// Get all tools in parallel
const [atpTools, nearTools, cryptoTools, searchTools] = await Promise.all([
atpToolset.getTools(),
nearToolset.getTools(),
cryptoToolset.getTools(),
braveSearchToolset.getTools(),
]);
// Create agent with combined tools from built-in and external servers
const defiAssistantAgent = new LlmAgent({
name: "defi_assistant_agent",
model: "gemini-2.5-flash",
description:
"A comprehensive assistant with blockchain, market data, and web search",
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
- Brave Search for web research
Use these tools to provide comprehensive insights`,
tools: [...atpTools, ...nearTools, ...cryptoTools, ...searchTools],
});
// Always cleanup all connections
await Promise.all([
atpToolset.close(),
nearToolset.close(),
cryptoToolset.close(),
braveSearchToolset.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. See MCP Sampling for detailed usage |
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 External Servers
For external MCP servers (Anthropic's official servers, community servers, custom servers, etc.), use McpToolset directly to connect to and consume MCP servers. This provides full control over connection configuration, tool discovery, and filtering.
Universal Compatibility
McpToolset can connect to any MCP-compliant server. If it follows the Model Context Protocol specification, ADK-TS can use it.
Note: This is for connecting TO existing MCP servers, not for creating them. See "Creating MCP Servers with ADK-TS" below for building your own 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. See MCP Sampling for detailed usage |
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)
Used for locally installed MCP servers that run as separate processes. This is the most common mode for external servers:
import { McpToolset, LlmAgent, type McpConfig } from "@iqai/adk";
// Connect to Anthropic's filesystem server
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)
Used for MCP servers hosted remotely over HTTP/HTTPS. This mode is less common but useful for cloud-hosted or centralized MCP services:
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
Choose the right approach based on your needs:
Use Wrapper Functions when:
- Connecting to IQ AI's pre-built servers (ATP, NEAR, Fraxlend, etc.)
- You want automatic configuration and connection management
- Configuration is simple (mostly environment variables)
- You want the quickest setup
Use McpToolset when:
- Connecting to external MCP servers (Anthropic's official servers, community servers, etc.)
- You need fine-grained control over timeouts, retries, and caching
- Working with remote endpoints requiring custom headers
- Building custom tool filtering or schema adaptation
- The MCP server doesn't have a wrapper function
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-TS agents, Claude Desktop, etc.). ADK-TS provides a starter template using FastMCP for building MCP servers quickly.
Build Once, Use Everywhere
MCP servers you create with ADK-TS can be used by any MCP-compatible client, not just ADK-TS agents. Share your MCP servers with the community!
Quick Start
Create a new MCP server project using the ADK-TS CLI:
# Install the ADK-TS 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-TS Agents
Once created, connect to your custom MCP server from an ADK-TS 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
For detailed guidance on creating custom MCP servers:
- Creating Custom MCPs Guide - Complete tutorial with examples
- MCP Starter Template - Template source code
- MCP Integration Examples - Advanced patterns
- FastMCP Documentation - Detailed FastMCP usage
MCP Tools Best Practices
Follow these best practices when working with MCP servers in your agents:
Connection Management
-
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.const toolset = new McpToolset({ /* config */ }); try { const tools = await toolset.getTools(); // Use tools } finally { await toolset.close(); } -
Test External Servers Independently: Before integrating an external MCP server, test it standalone with
npxto ensure it works:# Test the server independently npx -y @modelcontextprotocol/server-filesystem /test/path
Configuration
-
Use Environment Variables for Credentials: Never hardcode sensitive data. Always use environment variables:
// ✅ Good const toolset = new McpToolset({ transport: { env: { API_KEY: process.env.API_KEY!, PATH: process.env.PATH || "", }, }, }); // ❌ Bad const toolset = new McpToolset({ transport: { env: { API_KEY: "sk-1234567890", // Hardcoded! }, }, }); -
Environment-Specific Configuration: Adjust timeouts and retries based on environment:
const isDev = process.env.NODE_ENV === "development"; const toolset = new McpToolset({ timeout: isDev ? 10000 : 30000, retryOptions: { maxRetries: isDev ? 1 : 3, initialDelay: isDev ? 100 : 500, }, transport: { /* ... */ }, }); -
Verify Required Environment Variables: Check that all required variables are set before initializing:
const requiredVars = ["API_KEY", "DATABASE_URL"]; const missing = requiredVars.filter(v => !process.env[v]); if (missing.length > 0) { throw new Error(`Missing required env vars: ${missing.join(", ")}`); }
Tool Management
-
Filter Tools When Needed: Load only the tools your agent needs to improve performance and reduce LLM confusion:
// Only load specific tools const toolset = new McpToolset( config, ["read_file", "write_file"], // Filter by tool names ); // Or use a custom filter function const toolset = new McpToolset(config, tool => tool.name.startsWith("search_"), ); -
Choose the Right Approach:
- Use wrapper functions for IQ AI's built-in servers (simpler, faster setup)
- Use
McpToolsetfor external servers (more control, universal compatibility)
Error Handling
-
Handle Errors Gracefully: Implement proper error handling and provide fallbacks:
try { const tools = await toolset.getTools(); } catch (error) { if (error.code === "CONNECTION_ERROR") { console.error("Failed to connect to MCP server"); // Fallback to default tools } else if (error.code === "TIMEOUT_ERROR") { console.error("MCP server connection timed out"); // Retry with longer timeout } else { throw error; } } -
Return Structured Error Responses: In custom MCP tools, return structured errors:
export const myTool = { name: "my_operation", execute: async ({ input }) => { try { const result = await performOperation(input); return { success: true, data: result }; } catch (error) { return { success: false, error: { code: "OPERATION_FAILED", message: error instanceof Error ? error.message : "Unknown error", }, }; } }, };
Production Considerations
-
Implement Timeouts: Set appropriate timeouts for MCP operations:
const toolset = new McpToolset({ timeout: 30000, // 30 seconds retryOptions: { maxRetries: 3, initialDelay: 500, maxDelay: 5000, }, transport: { /* ... */ }, }); -
Monitor Resource Usage: Track MCP connections and cleanup:
const activeConnections = new Set(); async function createToolset(config) { const toolset = new McpToolset(config); activeConnections.add(toolset); return toolset; } // Cleanup on shutdown process.on("SIGINT", async () => { await Promise.all(Array.from(activeConnections).map(t => t.close())); process.exit(0); }); -
Log MCP Operations: Enable debug logging in development:
const toolset = new McpToolset({ debug: process.env.NODE_ENV === "development", transport: { /* ... */ }, });
MCP Tools Troubleshooting
Here are common issues when working with MCP tools and how to resolve them:
| 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
📦 IQ AI's Built-in MCP Servers
Explore IQ AI's suite of pre-built MCP servers with wrapper functions
🌐 Using External MCP Servers
Connect to Anthropic's official servers and community MCP servers
🛠️ Creating Custom MCP Servers
Build your own MCP servers with FastMCP and the starter template
🔧 Function Tools
Create custom ADK-TS tools for MCP integration
📚 Model Context Protocol
Official MCP specification and ecosystem resources