zapper-mcp
zapper-mcp
MCP-сервер, который предоставляет API портфелей DeFi Zapper в качестве продуманного набора инструментов для клиентов LLM. Подключите его к Claude Desktop или любому другому хосту, совместимому с MCP, и задавайте вопросы на естественном языке о любом кошельке — «сколько стоит этот кошелек?», «есть ли у него позиции в Aave?», «покажи мне основные активы в сети Base».
Создан на 9-й день 21-дневного спринта по AI-инжинирингу. На 10-й день этот сервер будет интегрирован в агент Mastra.
Набор инструментов
Обоснование дизайна для каждого примитива находится в DESIGN.md. Краткая версия:
Примитив | Название | Почему выбрано это место |
Инструмент |
| Вызывается моделью, динамически для каждого адреса, возвращает полную разбивку токенов + DeFi |
Инструмент |
| Специализированный инструмент для вопросов о спотовых токенах; позволяет модели не парсить весь портфель, когда нужны только активы в токенах |
Инструмент |
| Специализированный инструмент для вопросов о DeFi; отделен от |
Ресурс |
| Статический список сетей — хост внедряет его как контекст при сборке промпта, чтобы модель знала допустимые названия сетей без лишних вызовов инструментов |
Промпт |
| Инициируемый пользователем рабочий процесс, который подготавливает почву для многоходового анализа портфеля с ролью аналитика, инвентаризацией инструментов и адресом кошелька |
Почему не один большой инструмент get_everything? Объединение инструментов заставило бы модель получать и парсить большой ответ со смешанной схемой для каждого вопроса, даже для узкоспециализированных. Граница инструмента — это декларация области видимости: правильный инструмент возвращает именно то, что нужно для этапа рассуждения.
Почему API-ключ находится в конфигурации сервера, а не в аргументах инструмента? Учетные данные должны находиться на уровне хоста (переменные окружения, внедряемые при запуске процесса), а не в протоколе MCP. Если бы api_key был параметром инструмента, он проходил бы через рассуждения LLM и появлялся бы в истории диалога. Для многопользовательского развертывания правильным механизмом является аутентификация на транспортном уровне (Bearer-токен через Streamable HTTP) или OAuth для каждого пользователя — и то, и другое выходит за рамки данного проекта. См. Известные ограничения.
Related MCP server: Ankr API MCP Server
Требования
Node.js 20+
pnpm
Установка
git clone https://github.com/mehdi-loup/zapper-mcp
cd zapper-mcp
pnpm install
pnpm buildКонфигурация
Скопируйте .env.example в .env и добавьте свой ключ:
cp .env.example .env
# edit .env and set ZAPPER_API_KEY=your_key_hereСервер завершает работу при загрузке, если отсутствует ZAPPER_API_KEY — вы увидите ошибку сразу, а не при первом вызове инструмента.
Запуск
Автономный дымовой тест (подтверждает, что все работает без Claude Desktop):
ZAPPER_API_KEY=your_key pnpm clientВывод: список инструментов/ресурсов/промптов, затем вызов каждого инструмента для vitalik.eth.
Прямой запуск сервера:
ZAPPER_API_KEY=your_key pnpm startНастройка Claude Desktop
Добавьте в ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"zapper-mcp": {
"command": "node",
"args": ["/absolute/path/to/zapper-mcp/build/server.js"],
"env": {
"ZAPPER_API_KEY": "your_key_here"
}
}
}
}Перезапустите Claude Desktop. Три инструмента, ресурс zapper://supported-networks и промпт analyze-wallet станут доступны.
Логи (если сервер не загружается):
~/Library/Logs/Claude/mcp-server-zapper-mcp.logИнтеграция с Mastra (День 10)
Чтобы подключить этот сервер к агенту Mastra через MCP-клиент Mastra:
Запустите сервер:
node /path/to/build/server.jsНастройте MCP-клиент Mastra с транспортом stdio, имя сервера
zapper-mcpАгент получает данные Zapper исключительно через MCP —
lib/zapper.tsв репозитории агента становится неиспользуемым
Не все инструменты должны быть доступны агенту Mastra; это решение принимается на 10-й день проектирования.
Справочник инструментов
get_portfolio(address, networks?)
Полная разбивка портфеля: общая сумма в USD, все активы в токенах, все позиции DeFi.
address — wallet address or ENS name
networks — optional array: ["ethereum", "base", "arbitrum", ...]get_token_balances(address, networks?)
Только балансы спотовых токенов (без позиций DeFi).
get_app_positions(address, networks?, app_slug?)
Только позиции в приложениях DeFi (Aave, Uniswap, Sablier и т.д.).
app_slug — optional filter: "aave-v3", "uniswap-v3", ...Ресурс: zapper://supported-networks
JSON-массив { name, chainId } для всех проиндексированных сетей. Считывается хостом во время сборки контекста.
Промпт: analyze-wallet
Подготавливает почву для диалога по анализу портфеля. Принимает аргумент address.
Обработка ошибок
Каждый инструмент возвращает isError: true с сообщением, понятным для модели, в следующих случаях:
HTTP 401 / неверный API-ключ
HTTP 429 / превышение лимита запросов
HTTP 5xx / ошибка сервера Zapper
Тайм-аут сети (15 с)
Некорректный ответ
Пустой кошелек (totalUSD: 0, tokens: []) возвращает isError: false — пустота не является ошибкой.
Известные ограничения
Модель доверия с одним ключом: сервер хранит один
ZAPPER_API_KEYи обслуживает одного владельца. Для многопользовательского развертывания требуется OAuth для каждого пользователя или аутентификация на транспортном уровне (Streamable HTTP с Bearer-токенами).Отсутствие кэширования: каждый вызов инструмента обращается к API Zapper. Промышленный сервер добавил бы кэш с коротким TTL (позиции меняются медленно) и проактивно соблюдал бы лимиты запросов.
Нет
resources/subscribe:zapper://supported-networks— это статический список. Для обновлений в реальном времени сервер должен был бы объявлять о возможности подписки и отправлятьnotifications/resources/updated.Только транспорт stdio: транспорт Streamable HTTP отложен до будущих итераций.
Ограничение пагинации: инструменты возвращают до 50 токенов и 20 позиций приложений за запрос.
Что дальше
День 10: подключение этого сервера к агенту кошелька Mastra в ../day1-wallet-agent/ через MCP-клиент Mastra. Агент будет потреблять данные Zapper исключительно через MCP, подтверждая, что набор инструментов действительно отделяет функциональность от фреймворка агента.
Available Tools
3 toolsget_app_positionsA
DeFi app positions only (Aave lending, Uniswap LP, staking, etc.). Use when the question is about protocol exposure: 'any leveraged positions?', 'Aave borrows?', 'LP positions on Uniswap?'. Optionally filter by app slug.
| Name | Required | Description | Default |
|---|---|---|---|
| address | Yes | Wallet address or ENS name | |
| networks | No | Networks to filter by. Supported: ethereum, base, optimism, arbitrum, polygon, bnb, avalanche, zora. Omit for all networks. | |
| app_slug | No | Filter to a specific app slug, e.g. 'aave-v3', 'uniswap-v3' |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries full burden but does not disclose behavioral traits such as read-only nature, data freshness, or performance characteristics. The description only mentions filtering capabilities, which is adequate but not comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two sentences: first defines scope, second provides usage context and optional filter. Every sentence earns its place with no redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With no output schema, the description does not explain return values. However, given the tool's simplicity (3 params, 1 required) and clear purpose, the description is largely complete. Minor gap in output expectations.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Input schema has 100% coverage with descriptions for each parameter. The description does not add semantic value beyond the schema, simply restating the optional app_slug filter. Baseline score of 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description explicitly states 'DeFi app positions only' and lists examples (Aave, Uniswap, staking), clearly distinguishing it from sibling tools like get_portfolio and get_token_balances.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description directly tells when to use the tool ('when the question is about protocol exposure') and provides example queries ('any leveraged positions?', 'Aave borrows?', 'LP positions on Uniswap?'), effectively guiding the agent.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_portfolioA
Full portfolio breakdown for a wallet: total USD value, all token holdings, and all DeFi app positions across networks. Use this when the user wants a complete picture of what a wallet holds.
| Name | Required | Description | Default |
|---|---|---|---|
| address | Yes | Wallet address or ENS name | |
| networks | No | Networks to filter by. Supported: ethereum, base, optimism, arbitrum, polygon, bnb, avalanche, zora. Omit for all networks. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so description carries full burden. Discloses output (breakdown) but no information about side effects, permissions, rate limits, or data freshness. Lacks behavioral context.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two concise sentences. First describes output, second specifies usage context. No wasted words, front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
No output schema, so description must compensate. It explains return includes USD value, tokens, DeFi positions, but lacks detail on structure (e.g., token amounts, symbols). Adequate but not thorough.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, so baseline is 3. Description adds little beyond schema: repeats networks list and 'Omit for all networks' which is already in the schema description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool provides a full portfolio breakdown including total USD value, token holdings, and DeFi positions. It distinguishes itself from siblings (get_app_positions, get_token_balances) which are subsets.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly says to use when user wants a complete picture of wallet holdings. Does not list when to avoid using or mention alternatives, but context is clear.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_token_balancesA
Spot token balances only (no DeFi positions). Use when the question is specifically about token holdings: 'does this wallet hold ETH?', 'how much USDC is on Base?'
| Name | Required | Description | Default |
|---|---|---|---|
| address | Yes | Wallet address or ENS name | |
| networks | No | Networks to filter by. Supported: ethereum, base, optimism, arbitrum, polygon, bnb, avalanche, zora. Omit for all networks. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries full burden. It discloses the scope (spot tokens only) but does not mention any other behavioral traits such as rate limits, authentication requirements, or response format. Acceptable but could be more comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two short, front-loaded sentences with no redundant information. Every word contributes to clarity and utility.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool has only two parameters and no output schema, the description is reasonably complete: it states scope, use cases, and exclusions. It could briefly hint at output structure, but that is not critical for this simple tool.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100%, so baseline is 3. The description adds minor value by providing usage examples but does not elaborate on parameter semantics beyond what the schema already provides.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool returns 'spot token balances only' and explicitly excludes DeFi positions, distinguishing it from siblings like get_app_positions. It also provides specific example queries, making the purpose unambiguous.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly says 'Use when the question is specifically about token holdings' and gives concrete examples. It implies when not to use (DeFi positions) but does not directly name alternative tools for that case. Still, the guidance is clear and helpful.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
TDQS
Each tool targets a distinct aspect of wallet data: token balances, DeFi positions, or full portfolio. Descriptions clearly differentiate them, leaving no ambiguity for an agent.
All tools follow a consistent 'get_<descriptive_noun>' pattern (get_app_positions, get_portfolio, get_token_balances), making naming predictable and readable.
Three tools is well-scoped for a wallet data server, covering the core needs without excess or deficiency.
The set covers token balances, DeFi positions, and a combined portfolio, which forms a complete picture for most wallet queries. Missing advanced features like transaction history are acceptable for the scope.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
MCP server giving AI agents one-connection access to crypto & DeFi data: DeFi protocol TVL, stableco
Hosted MCP server connecting AI assistants to 9,000+ apps and 40,000+ actions via Zapier.
MCP server connecting AI agents to non-custodial staking data across 130+ networks.
An MCP server that provides an API to LLMs to manage their JumpCloud resources.
Related MCP Servers
- AlicenseBqualityDmaintenanceAn MCP server that enables LLMs to perform blockchain operations on the Base network through natural language commands, including wallet management, balance checking, and transaction execution.4273MIT
- AlicenseBqualityCmaintenanceAn MCP server that fetches on-chain blockchain data via the Ankr API, allowing LLMs to retrieve token balances for wallet addresses on specific networks.1253MIT
- AlicenseAqualityDmaintenanceAn MCP server that empowers AI agents to inspect any wallet’s balance and onchain activity across major EVM chains and Solana chain.39MIT
- AlicenseNot gradedqualityDmaintenanceMCP server that provides live crypto portfolio data, token info, gas prices, swap offers, and Bitcoin balance via Zerion and Blockstream APIs.3MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/mehdi-loup/zapper-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server