query-graphql
Execute GraphQL queries with specified variables and headers using a configurable endpoint. Simplifies interaction with GraphQL servers for data retrieval and manipulation.
Instructions
Query a GraphQL endpoint with the given query and variables
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| endpoint | No | Optional: Override the default endpoint, the already used endpoint is: http://localhost:3000/graphql | |
| headers | No | Optional: Add additional headers, the already used headers are: {} | |
| query | Yes | ||
| variables | No |
Implementation Reference
- src/index.ts:124-214 (handler)Executes the GraphQL query: parses the query to check for mutations (disabled by default), sends a POST request to the configured endpoint with query and variables, handles HTTP/GraphQL errors, and returns formatted JSON response.async ({ query, variables }) => { try { const parsedQuery = parse(query); // Check if the query is a mutation const isMutation = parsedQuery.definitions.some( (def) => def.kind === "OperationDefinition" && def.operation === "mutation", ); if (isMutation && !env.ALLOW_MUTATIONS) { return { isError: true, content: [ { type: "text", text: "Mutations are not allowed unless you enable them in the configuration. Please use a query operation instead.", }, ], }; } } catch (error) { return { isError: true, content: [ { type: "text", text: `Invalid GraphQL query: ${error}`, }, ], }; } try { const response = await fetch(env.ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", ...env.HEADERS, }, body: JSON.stringify({ query, variables, }), }); if (!response.ok) { const responseText = await response.text(); return { isError: true, content: [ { type: "text", text: `GraphQL request failed: ${response.statusText}\n${responseText}`, }, ], }; } const data = await response.json(); if (data.errors && data.errors.length > 0) { // Contains GraphQL errors return { isError: true, content: [ { type: "text", text: `The GraphQL response has errors, please fix the query: ${JSON.stringify( data, null, 2, )}`, }, ], }; } return { content: [ { type: "text", text: JSON.stringify(data, null, 2), }, ], }; } catch (error) { throw new Error(`Failed to execute GraphQL query: ${error}`); } },
- src/index.ts:120-123 (schema)Input schema using Zod: 'query' (required string) and 'variables' (optional string).{ query: z.string(), variables: z.string().optional(), },
- src/index.ts:117-119 (registration)Registers the 'query-graphql' tool with McpServer.tool(), providing name, description, input schema, and handler function.server.tool( "query-graphql", "Query a GraphQL endpoint with the given query and variables",