APIForge MCP Server
Automatically generates MCP tools from JSON API configs, manages authentication (API Key, OAuth 2.0), and controls access for AI agents like Hermes.
README
APIForge MCP Server
MCP-сервер для интеграции API-сервисов с Hermes Agent и другими MCP-клиентами.
Зачем это нужно
Hermes Agent — это AI-агент, который работает с инструментами через MCP (Model Context Protocol). Но для работы с реальными API (Яндекс Метрика, Search Console и др.) нужен прослойка, который:
- Генерирует инструменты автоматически из JSON-конфигов API
- Управляет аутентификацией (API Key, OAuth 2.0)
- Контролирует доступ — какие инструменты доступны агенту
Архитектура
Hermes Agent (MCP Client)
│
MCP Server (Python SDK)
┌────┴────┐
│ Tools │ ← генерируются из JSON-конфигов
│ Auth │ ← API Key / OAuth 2.0
│ Access │ ← allow/deny по инструментам
└────┬────┘
│
HTTP (httpx)
│
┌────┴────┐
│ Yandex │
│ Google │
│ Custom │
└─────────┘
Быстрый старт
# Установка
cd mcp-server
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
# Запуск (STDIO — для Hermes)
python -m apiforge_mcp.server
# Запуск (HTTP/SSE — удалённый доступ)
APIFORGE_TRANSPORT=sse python -m apiforge_mcp.server
Конфигурация
Конфиги API
Файлы в configs/ определяют доступные API и их параметры:
// configs/yandex_metrika.json
{
"base_url": "https://api-metrika.yandex.net",
"auth": { "type": "oauth" },
"resources": {
"counters_list": {
"path": "/management/v1/counters",
"method": "GET",
"description": "List all counters"
},
"counter_stat": {
"path": "/stat/v1/data",
"method": "GET",
"description": "Get statistics",
"parameters": {
"id": { "type": "integer", "required": true, "description": "Counter ID" },
"metrics": { "type": "string", "required": true, "description": "Metrics" }
}
}
}
}
Добавление нового API: просто кладёте JSON-файл в configs/. Инструменты генерируются автоматически.
Контроль доступа
// configs/access.json
{
"default_role": "readonly",
"tools": {
"allow": ["*"],
"deny": ["secret_*"]
},
"service_tools": {
"yandex_metrika": {
"allow": ["yandex_metrika_*"],
"deny": []
}
}
}
Уровни контроля:
- Global — правила для всех инструментов
- Service — правила для конкретного API
- Tool — конкретный инструмент
Приоритет: Tool > Service > Global. Deny всегда побеждает Allow.
Переменные окружения
# Аутентификация
YANDEX_METRIKA_API_KEY=your_api_key
YANDEX_METRIKA_AUTH_PROVIDER=api_key # или oauth
# Контроль доступа
APIFORGE_DEFAULT_ROLE=readonly # readonly | readwrite | admin
YANDEX_METRIKA_ROLE=readwrite # роль для конкретного сервиса
# Сервер
APIFORGE_TRANSPORT=stdio # stdio | sse
APIFORGE_HOST=127.0.0.1 # для SSE
APIFORGE_PORT=8080 # для SSE
APIFORGE_CONFIGS_DIR=./configs # путь к конфигам
Интеграция с Hermes Agent
STDIO (локальный запуск)
# ~/.hermes/config.yaml
mcp_servers:
apiforge:
command: python
args: ["-m", "apiforge_mcp.server"]
env:
YANDEX_METRIKA_API_KEY: ${YANDEX_METRIKA_API_KEY}
APIFORGE_DEFAULT_ROLE: readonly
HTTP/SSE (удалённый доступ)
# ~/.hermes/config.yaml
mcp_servers:
apiforge:
url: http://your-server:8080/sse
headers:
Authorization: Bearer ${MCP_TOKEN}
MCP Примитивы
Tools (инструменты)
Инструменты генерируются автоматически из конфигов:
| Инструмент | Описание | Метод |
|---|---|---|
yandex_metrika_counters_list |
Список счетчиков | GET |
yandex_metrika_counter_stat |
Статистика | GET |
yandex_metrika_goals |
Цели | GET |
yandex_search_console_hosts |
Хосты | GET |
yandex_search_console_search_queries |
Запросы | GET |
get_audit_log |
Лог аудита | - |
list_services |
Список сервисов | - |
Resources (документация для ИИ)
| Ресурс | Описание |
|---|---|
docs://guide |
Полное руководство по использованию |
docs://tools/{service} |
Документация по конкретному сервису |
docs://access |
Документация по контролю доступа |
docs://auth |
Документация по аутентификации |
ИИ может читать эти ресурсы через resources/read для получения контекста.
Prompts (шаблоны для ИИ)
| Промпт | Когда использовать |
|---|---|
analytics_query |
Запрос аналитических данных |
api_exploration |
Изучение доступных API |
troubleshooting |
Диагностика проблем |
ИИ может загружать эти промпты через prompts/get для получения инструкций.
Тестирование
# Все тесты
pytest tests/ -v
# Линтер
ruff check src/ tests/
Структура проекта
mcp-server/
├── configs/
│ ├── access.json # Правила доступа
│ ├── yandex_metrika.json # API Яндекс Метрики
│ └── yandex_search_console.json
├── src/apiforge_mcp/
│ ├── server.py # MCP сервер + динамическая генерация
│ ├── auth/
│ │ ├── manager.py # Менеджер аутентификации
│ │ ├── api_key.py # API Key провайдер
│ │ └── oauth.py # OAuth 2.0 провайдер
│ ├── access/
│ │ └── policy.py # Контроль доступа (roles + tools)
│ └── tools/
│ └── registry.py # Реестр инструментов
├── tests/
│ └── test_server.py # 32 теста
├── docs/
│ ├── adr/ # Architecture Decision Records
│ └── AI_REFERENCE.md # Справочник для ИИ
├── README.md # Основная документация
├── ARCHITECTURE.md # Архитектурные решения
├── CHANGELOG.md # История изменений
├── CONTRIBUTING.md # Как вносить вклад
├── SECURITY.md # Политика безопасности
├── RUNBOOK.md # Операционные процедуры
└── pyproject.toml
Ключевые решения
- Динамическая генерация — инструменты создаются из JSON, не хардкодятся
- APIForge как transport core — HTTP-запросы через httpx с retry
- Многоуровневый контроль доступа — glob-паттерны на 3 уровнях
- Асинхронность — все запросы async/await для производительности
- Аудит — логирование всех вызовов и отказов
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.