Build a CoinGecko Connector for Claude AI – Get Real-Time Cryptocurrency Data in Your AI Agent Using MCP Server
In the fast-paced world of cryptocurrency, having access to real-time data is crucial for traders, analysts, and developers building intelligent applications. With the rise of AI agents like Anthropic's Claude, there's an opportunity to combine natural language capabilities with live market data. This tutorial will guide you through creating a CoinGecko connector for Claude AI using the Model Context Protocol (MCP) server. By the end, you'll be able to fetch real-time cryptocurrency prices, market stats, and more directly inside your Claude-powered AI agent.
Introduction to the Key Technologies
Before diving into the integration, let's clarify the core components:
- CoinGecko: One of the most popular cryptocurrency APIs, providing data on thousands of coins, exchanges, and market metrics—including price, volume, market cap, and historical data.
- Claude AI: Anthropic's advanced AI assistant capable of reasoning, generating text, and now, with MCP, interacting with external tools and data sources.
- MCP Server: The Model Context Protocol (MCP) is an open protocol that standardizes how AI models connect to external tools and data. An MCP server acts as a bridge, exposing APIs like CoinGecko as tools that Claude can use.
- AI Agent: An autonomous or semi-autonomous system that can perform tasks, often using LLMs like Claude, enhanced with the ability to access real-world data.
By building this connector, you'll empower your AI agent to answer queries like "What's the current price of Bitcoin?" or "Show me the top gainers today" without leaving the conversation.
Why Use MCP with Claude?
MCP provides a universal interface for connecting AI models to external APIs. Instead of hardcoding API calls, MCP defines tools in a standardized format. Claude can then decide when and how to use those tools based on user prompts. This makes your AI agent more dynamic, maintainable, and scalable. With an MCP server for CoinGecko, Claude can fetch live crypto data on demand, ensuring responses are always up to date.
Prerequisites
To follow along, you'll need:
- An API key from CoinGecko (free tier available).
- Node.js and npm installed on your machine.
- Access to Claude with MCP support (via Anthropic's Workbench or compatible client).
- Basic familiarity with TypeScript/JavaScript and command-line tools.
Step 1: Setting Up the MCP Server
We'll build an MCP server in TypeScript that exposes CoinGecko endpoints as tools. Start by creating a new project:
mkdir coingecko-mcp-server
cd coingecko-mcp-server
npm init -y
Install the required dependencies:
npm install @modelcontextprotocol/sdk axios dotenv
npm install -D typescript @types/node ts-node
Initialize TypeScript:
npx tsc --init
Create a .env file to store your CoinGecko API key (use the free demo key if testing):
COINGECKO_API_KEY=YOUR_API_KEY_HERE
Step 2: Writing the MCP Server Code
Create a file src/index.ts. We'll define a server that registers a tool called get_crypto_price and one for get_trending_coins. The server will call the CoinGecko API and return results in a structured format.
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import axios from "axios";
import dotenv from "dotenv";
dotenv.config();
const COINGECKO_API_KEY = process.env.COINGECKO_API_KEY;
const BASE_URL = "https://api.coingecko.com/api/v3";
const server = new Server(
{
name: "coingecko-mcp-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
// Tool definitions
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "get_crypto_price",
description: "Get the current price and market data for a cryptocurrency by ID (e.g., bitcoin, ethereum).",
inputSchema: {
type: "object",
properties: {
coin_id: {
type: "string",
description: "The CoinGecko coin ID (lowercase). Example: 'bitcoin'."
},
vs_currency: {
type: "string",
description: "The target currency (default: usd)."
}
},
required: ["coin_id"]
}
},
{
name: "get_trending_coins",
description: "Get the top trending coins on CoinGecko (based on search interest).",
inputSchema: {
type: "object",
properties: {},
required: []
}
}
]
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
let result;
switch (name) {
case "get_crypto_price": {
const coinId = args?.coin_id as string;
const vsCurrency = (args?.vs_currency as string) || "usd";
const response = await axios.get(
`${BASE_URL}/simple/price`,
{
params: {
ids: coinId,
vs_currencies: vsCurrency,
include_market_cap: "true",
include_24hr_vol: "true",
include_24hr_change: "true",
x_cg_demo_api_key: COINGECKO_API_KEY,
},
}
);
result = response.data;
break;
}
case "get_trending_coins": {
const response = await axios.get(
`${BASE_URL}/search/trending`,
{
headers: {
accept: "application/json",
"x-cg-demo-api-key": COINGECKO_API_KEY,
},
}
);
result = response.data;
break;
}
default:
throw new Error(`Unknown tool: ${name}`);
}
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error: any) {
return {
content: [
{
type: "text",
text: `Error calling CoinGecko API: ${error.message}`,
},
],
isError: true,
};
}
});
// Start server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("CoinGecko MCP server running on stdio");
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
This code creates an MCP server that listens via standard I/O, registers two tools, and handles incoming calls.
Step 3: Building and Testing
Add a build script to package.json:
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
Compile TypeScript and test with:
npm run build
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | node dist/index.js
Step 4: Connecting to Claude
Now connect the server to Claude via the MCP configuration:
{
"mcpServers": {
"coingecko": {
"command": "node",
"args": ["dist/index.js"],
"cwd": "/path/to/coingecko-mcp-server"
}
}
}
After restarting Claude, ask: "What is the current price of Ethereum?" Claude will detect the tool, call it via MCP, and return a human-readable answer.
Step 5: Expanding the Connector
You can extend the connector with many CoinGecko endpoints:
- Market Data: Full market data for all coins with pagination.
- Historical Data: Historical prices at specific dates.
- Exchanges: Exchange listings and trading volumes.
- NFT Data: Floor prices and market stats for NFT collections.
- On-chain Data: Blockchain data for supported networks.
Best Practices for Production
- Rate Limiting: Implement caching (in-memory or Redis) to respect CoinGecko's rate limits.
- Error Handling: Gracefully handle API errors and timeouts.
- Security: Keep API keys in environment variables, never in client-side code.
- Logging: Add structured logging for debugging.
- Tool Descriptions: Write clear, precise descriptions so Claude knows when to invoke each tool.
Conclusion
Building a CoinGecko connector for Claude AI using an MCP server is a powerful way to bring real-time cryptocurrency data into your AI agent. With just a few hundred lines of TypeScript, you can give Claude the ability to answer crypto-market questions with live data. The MCP framework makes the integration clean, standardized, and extensible. Try it today and supercharge your AI agent with the data it needs to stay ahead in the crypto world.
Top comments (0)