mcp-graphql-bridge
mcp-graphql-bridge
Универсальный MCP-сервер (Model Context Protocol), который связывает любой GraphQL API с Claude Code. Он анализирует вашу схему GraphQL и предоставляет каждый запрос (query) и мутацию (mutation) в виде отдельного инструмента, позволяя Claude взаимодействовать с вашим API напрямую.
Как это работает
При запуске сервер:
Ищет файл
schema-introspection.jsonв рабочей директории (быстро, без сетевого вызова)Если файл не найден, выполняет интроспекцию в реальном времени по адресу
GRAPHQL_INTROSPECTION_URLРегистрирует по одному инструменту на каждый запрос (
query__<name>) и на каждую мутацию (mutation__<name>)Всегда регистрирует универсальный инструмент
execute_graphqlдля резервного выполнения и инструментget_type_detailsдля исследования схемы
Related MCP server: GraphQL MCP Server
Требования
Node.js >= 18
Настройка
Шаг 1: Установка
Вариант A: Установка из npm (рекомендуется)
npm install -g mcp-graphql-bridgeВариант B: Клонирование и сборка из исходного кода
git clone https://github.com/murilopereira/mcp-graphql-bridge.git
cd mcp-graphql-bridge
npm install
npm run buildШаг 2: Настройка переменных окружения
Переменная | Обязательно | Описание |
| Да | Эндпоинт для запросов и мутаций |
| Да | Эндпоинт для интроспекции схемы (может совпадать с предыдущим) |
| Да | Bearer-токен для аутентификации |
Вы можете задать их в файле .env в корне проекта:
GRAPHQL_API_URL=https://your-api.example.com/graphql
GRAPHQL_INTROSPECTION_URL=https://your-api.example.com/graphql
GRAPHQL_TOKEN=your-bearer-tokenИли передать их напрямую через команду claude mcp add (см. ниже).
Шаг 3: (Опционально) Предварительная генерация снимка схемы
По умолчанию сервер выполняет интроспекцию схемы при запуске — файл не требуется. Используйте этот шаг только в том случае, если в вашем API отключена интроспекция в продакшене или если вы хотите ускорить время запуска:
curl -s -X POST https://your-api.example.com/graphql \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-bearer-token" \
-d '{"query":"{ __schema { queryType { fields { name description args { name description defaultValue type { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } type { kind name ofType { kind name ofType { kind name } } } } } mutationType { fields { name description args { name description defaultValue type { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } type { kind name ofType { kind name ofType { kind name } } } } } } }"}' \
> schema-introspection.jsonДобавление в Claude Code
Вариант A: Область пользователя (только для вас)
Если установлено из npm:
claude mcp add --transport stdio \
--env GRAPHQL_API_URL=https://your-api.example.com/graphql \
--env GRAPHQL_INTROSPECTION_URL=https://your-api.example.com/graphql \
--env GRAPHQL_TOKEN=your-bearer-token \
graphql-bridge -- mcp-graphql-bridgeЕсли клонировано из исходного кода:
claude mcp add --transport stdio \
--env GRAPHQL_API_URL=https://your-api.example.com/graphql \
--env GRAPHQL_INTROSPECTION_URL=https://your-api.example.com/graphql \
--env GRAPHQL_TOKEN=your-bearer-token \
graphql-bridge -- node /absolute/path/to/mcp-graphql-bridge/dist/index.jsВажно: Убедитесь, что используете
mcp-graphql-bridge/dist/index.js(скомпилированный результат), а неmcp-graphql-bridge/index.js. Исходный код на TypeScript должен быть сначала собран с помощьюnpm run build, а точка входа находится в папкеdist/.
Вариант B: Область проекта (общий доступ для команды через .mcp.json)
claude mcp add --transport stdio --scope project \
--env GRAPHQL_API_URL=https://your-api.example.com/graphql \
--env GRAPHQL_INTROSPECTION_URL=https://your-api.example.com/graphql \
--env GRAPHQL_TOKEN=your-bearer-token \
graphql-bridge -- mcp-graphql-bridgeПримечание: Используйте абсолютные пути. Все флаги
--envи--transportдолжны идти перед именем сервера.
Проверка соединения
claude mcp listЗатем в сессии Claude Code выполните /mcp, чтобы увидеть доступные серверы и инструменты.
Доступные инструменты
Инструмент | Описание |
| Один инструмент на каждое поле запроса GraphQL |
| Один инструмент на каждое поле мутации GraphQL |
| Универсальный инструмент — выполнение любого запроса или мутации |
| Исследование полей конкретного типа GraphQL |
Все инструменты для операций принимают специальный аргумент __fields, в котором можно указать пользовательский набор полей GraphQL (например, { id name status }). Если аргумент опущен, возвращаются только скалярные поля.
Docker
Сборка образа
docker build -t mcp-graphql-bridge .Добавление в Claude Code через Docker
claude mcp add --transport stdio \
--env GRAPHQL_API_URL=https://your-api.example.com/graphql \
--env GRAPHQL_INTROSPECTION_URL=https://your-api.example.com/graphql \
--env GRAPHQL_TOKEN=your-bearer-token \
graphql-bridge -- docker run -i --rm \
-e GRAPHQL_API_URL -e GRAPHQL_INTROSPECTION_URL -e GRAPHQL_TOKEN \
mcp-graphql-bridgeПримечание: Флаг
-i(без-t) обязателен — он оставляет stdin открытым для протокола MCP stdio.
Разработка
npm run dev # watch mode: rebuilds and restarts on file changes
npm run build # one-off TypeScript compile
npm start # run the compiled serverУстранение неполадок
Ошибка: Cannot find module '.../index.js'
Если вы видите ошибку вида:
Error: Cannot find module '/path/to/mcp-graphql-bridge/index.js'Вы указываете не на тот файл. Исходный код на TypeScript должен быть сначала скомпилирован, а точка входа находится в папке dist/:
Правильный путь: /path/to/mcp-graphql-bridge/dist/index.js
Неправильный путь: /path/to/mcp-graphql-bridge/index.js
Решение:
Убедитесь, что вы выполнили
npm run build(создается папкаdist/)Обновите конфигурацию MCP, чтобы использовать полный путь, заканчивающийся на
/dist/index.js
Ошибка интроспекции схемы
Если сервер запускается, но показывает "Schema introspection failed", возможно, в вашем GraphQL API отключена интроспекция в продакшене. Используйте команду curl из шага 3 раздела "Настройка", чтобы предварительно сгенерировать файл schema-introspection.json.
Инструменты не появляются в Claude Code
Выполните
claude mcp list, чтобы убедиться, что сервер зарегистрированВыполните
/mcpв сессии Claude Code, чтобы увидеть доступные инструментыПроверьте, что заданы все необходимые переменные окружения (
GRAPHQL_API_URL,GRAPHQL_INTROSPECTION_URL,GRAPHQL_TOKEN)
Available Tools
2 toolsexecute_graphqlA
Execute any GraphQL query or mutation against the API. Use this when no specific tool exists for your operation.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | Full GraphQL query or mutation string including selection set | |
| variables | No | Variables for the operation | |
| bearer_token | No | Bearer token to authenticate this request (overrides GRAPHQL_TOKEN) | |
| custom_headers | No | Additional request headers as key-value pairs, e.g. {"X-Tenant-ID": "abc"} |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so description must disclose behavioral traits. It does not mention potential side effects of mutations, authentication requirements (beyond parameter hints), rate limits, or error handling. The description is too minimal to convey safe usage.
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 sentences pack purpose and usage guidelines with zero waste, frontloading the key action and fallback use.
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; description does not explain return format, errors, or the fact that the endpoint is pre-configured. Despite the complexity of a generic GraphQL executor, the description is incomplete.
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 description coverage is 100% (all 4 parameters have descriptions). The description adds no additional parameter semantics. Baseline 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 clearly states 'Execute any GraphQL query or mutation against the API', specifying the verb and resource. It distinguishes itself from sibling 'get_type_details' by being a generic executor.
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 'Use this when no specific tool exists for your operation', providing clear when-to-use guidance. No exclusions, but the instruction is direct.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_type_detailsB
Get fields of a specific GraphQL type to know what to put in __fields
| Name | Required | Description | Default |
|---|---|---|---|
| typeName | Yes | GraphQL type name, e.g. 'Repository', 'User', 'Issue' |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description must disclose all behavioral traits. It indicates a read operation, but does not mention error handling (e.g., invalid type name), response structure, or any side effects.
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 a single, focused sentence with no extraneous text. It is front-loaded and efficient.
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?
Despite the tool's simplicity, the description omits output details. The agent does not know whether the response returns field names, types, or full schema; this is critical given no output schema.
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?
The schema already covers the single parameter with a clear description and examples. The tool description adds no extra meaning beyond prompting usage of '__fields'.
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 gets fields of a specific GraphQL type and its purpose in GraphQL introspection. However, it does not differentiate from sibling tool execute_graphql, which may also retrieve type information.
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 phrase 'to know what to put in __fields' implies a use case, but there is no explicit guidance on when to use this tool versus execute_graphql, nor any when-not-to-use advice.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
2 tool updates
v2.1.0- Changed
execute_graphql2 fields changed- added
Input schema / properties / bearer_tokenAdded value: +{ + "description": "Bearer token to authenticate this request (overrides GRAPHQL_TOKEN)", + "type": "string" +} - added
Input schema / properties / custom_headersAdded value: +{ + "additionalProperties": { + "type": "string" + }, + "description": "Additional request headers as key-value pairs, e.g. {\"X-Tenant-ID\": \"abc\"}", + "type": "object" +}
- Changed
get_type_details1 field changed- changed
Input schema / properties / typeName / descriptionPrevious value: -"GraphQL type name, e.g. 'Machine', 'WorkOrder', 'Shift'"New value: +"GraphQL type name, e.g. 'Repository', 'User', 'Issue'"
2 tool updates
v1.0.1- First observed
execute_graphql - First observed
get_type_details
TDQS
Scored across 2 tools
The two tools serve clearly distinct purposes: executing GraphQL operations vs. retrieving type metadata. No overlap in functionality.
Both tool names follow a consistent verb_noun pattern using snake_case (execute_graphql, get_type_details), making the intent clear and predictable.
For a GraphQL bridge, two tools is minimal but still covers the essential operations of executing queries and exploring types. Slightly under-scoped but reasonable.
The tool surface covers core GraphQL operations (any query/mutation) and type introspection. Minor gaps exist (e.g., no dedicated tool for listing mutations), but the generic execute tool and type details suffice for agents familiar with GraphQL.
Maintenance
Related MCP Connectors
The Grafbase MCP server sits in front of a GraphQL API and exposes an MCP protocol-compliant interface that allows AI agents and LLMs to explore and query GraphQL APIs using natural language. It provides tools to search schemas, introspect types and fields, and execute GraphQL queries while minimizing context bloat by returning only relevant schema subsets, with built-in support for authentication, authorization, and configurable access control.
An MCP server that provides an API to LLMs to manage their JumpCloud resources.
- QuallaaOAuthcom.quallaa
Talk to your public-facing AI from any MCP client — Claude, ChatGPT, Cursor, Cline, Windsurf.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceA MCP server that exposes GraphQL schema information to LLMs like Claude. This server allows an LLM to explore and understand large GraphQL schemas through a set of specialized tools, without needing to load the whole schema into the context23 npm46MIT
- AlicenseCqualityDmaintenanceA TypeScript server that provides Claude AI with seamless access to any GraphQL API through the Model Context Protocol.611 npm12MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables LLMs to interact with GraphQL APIs by providing schema introspection and query execution capabilities.889 npm3MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables LLMs to interact with GraphQL APIs by providing schema introspection and query execution capabilities.2 npmMIT