Skip to main content
Glama
ivo-toby

Contentful GraphQL MCP Server

graphql_query

Execute GraphQL queries to retrieve content from Contentful's Content Delivery API, enabling flexible and efficient data fetching with read-only access.

Instructions

IMPORTANT: Before using this tool, you MUST first use graphql_list_content_types and graphql_get_content_type_schema to understand the available content types and their structure. Execute a GraphQL query against the Contentful GraphQL API. This tool allows you to use Contentful's powerful GraphQL interface to retrieve content in a more flexible and efficient way than REST API calls. The space ID and CDA token are automatically retrieved from environment variables.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe GraphQL query string to execute (must be a valid GraphQL query)
variablesNoOptional variables for the GraphQL query
spaceIdNoOptional override for the space ID (defaults to SPACE_ID environment variable)
environmentIdNoOptional override for the environment ID (defaults to ENVIRONMENT_ID environment variable or 'master')

Implementation Reference

  • Main handler function `executeQuery` that executes the provided GraphQL query against Contentful's GraphQL API using delivery token. Supports schema validation if cached, handles variables, environment overrides, and returns formatted ToolResponse with JSON data or errors.
    executeQuery: async (args: GraphQLQueryArgs): Promise<ToolResponse> => {
      try {
        // Get values from environment variables with optional overrides
        const spaceId = args.spaceId || process.env.SPACE_ID
        const environmentId = args.environmentId || process.env.ENVIRONMENT_ID || "master"
        const accessToken = process.env.CONTENTFUL_DELIVERY_ACCESS_TOKEN
    
        if (!spaceId) {
          return {
            content: [
              {
                type: "text",
                text: "Space ID is required (set SPACE_ID environment variable or provide spaceId parameter)",
              },
            ],
            isError: true,
          }
        }
    
        if (!accessToken) {
          return {
            content: [
              {
                type: "text",
                text: "Content Delivery API (CDA) token is required for GraphQL queries (set CONTENTFUL_DELIVERY_ACCESS_TOKEN environment variable)",
              },
            ],
            isError: true,
          }
        }
    
        // Validate the query against the schema if available
        if (graphqlSchema) {
          try {
            const queryDocument = parse(args.query)
            const validationErrors = validate(graphqlSchema, queryDocument)
    
            if (validationErrors.length > 0) {
              return {
                content: [
                  {
                    type: "text",
                    text: JSON.stringify(
                      {
                        errors: validationErrors.map((error) => ({ message: error.message })),
                      },
                      null,
                      2,
                    ),
                  },
                ],
                isError: true,
              }
            }
          } catch (parseError) {
            return {
              content: [
                {
                  type: "text",
                  text: JSON.stringify(
                    {
                      errors: [{ message: `GraphQL query parsing error: ${parseError}` }],
                    },
                    null,
                    2,
                  ),
                },
              ],
              isError: true,
            }
          }
        } else {
          console.warn("GraphQL schema not available for validation")
        }
    
        // Execute the query against the Contentful GraphQL API
        const endpoint = `https://graphql.contentful.com/content/v1/spaces/${spaceId}/environments/${environmentId}`
    
        const response = await fetch(endpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${accessToken}`,
          },
          body: JSON.stringify({
            query: args.query,
            variables: args.variables || {},
          }),
        })
    
        // Handle HTTP error responses
        if (!response.ok) {
          const errorText = await response.text()
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(
                  {
                    errors: [{ message: `HTTP Error ${response.status}: ${errorText}` }],
                  },
                  null,
                  2,
                ),
              },
            ],
            isError: true,
          }
        }
    
        const result = (await response.json()) as GraphQLExecuteResponse
    
        console.error("GraphQL response:", JSON.stringify(result))
    
        // Check for GraphQL errors
        if (result.errors) {
          const errorResponse = {
            content: [
              {
                type: "text",
                text: JSON.stringify(
                  {
                    errors: result.errors,
                  },
                  null,
                  2,
                ),
              },
            ],
            isError: true,
          }
          console.error("Returning error response:", JSON.stringify(errorResponse))
          return errorResponse
        }
    
        // Return the successful result
        const successResponse = {
          content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
        }
        console.error("Returning success response:", JSON.stringify(successResponse))
        return successResponse
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  errors: [
                    {
                      message: `Error executing GraphQL query: ${error instanceof Error ? error.message : String(error)}`,
                    },
                  ],
                },
                null,
                2,
              ),
            },
          ],
          isError: true,
        }
      }
  • Tool schema definition for 'graphql_query' including name, description, and inputSchema with required 'query' string and optional 'variables' object, plus env overrides.
    GRAPHQL_QUERY: {
      name: "graphql_query",
      description:
        "IMPORTANT: Before using this tool, you MUST first use graphql_list_content_types and graphql_get_content_type_schema to understand the available content types and their structure. Execute a GraphQL query against the Contentful GraphQL API. This tool allows you to use Contentful's powerful GraphQL interface to retrieve content in a more flexible and efficient way than REST API calls. The space ID and CDA token are automatically retrieved from environment variables.",
      inputSchema: getOptionalEnvProperties({
        type: "object",
        properties: {
          query: {
            type: "string",
            description: "The GraphQL query string to execute (must be a valid GraphQL query)",
          },
          variables: {
            type: "object",
            description: "Optional variables for the GraphQL query",
            additionalProperties: true,
          },
        },
        required: ["query"],
      }),
    },
  • src/index.ts:118-131 (registration)
    Registration of 'graphql_query' tool to graphqlHandlers.executeQuery in the main stdio server's getHandler function.
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function getHandler(name: string): ((args: any) => Promise<any>) | undefined {
      const cdaOnlyHandlers = {
        // Only GraphQL operations are allowed with just a CDA token
        graphql_query: graphqlHandlers.executeQuery,
        graphql_list_content_types: graphqlHandlers.listContentTypes,
        graphql_get_content_type_schema: graphqlHandlers.getContentTypeSchema,
        graphql_get_example: graphqlHandlers.getExample,
        smart_search: graphqlHandlers.smartSearch,
        build_search_query: graphqlHandlers.buildSearchQuery,
      }
    
      return cdaOnlyHandlers[name as keyof typeof cdaOnlyHandlers]
    }
  • Registration of 'graphql_query' tool to graphqlHandlers.executeQuery in the StreamableHTTP server's getHandler function.
    private getHandler(name: string):
      | ((args: Record<string, unknown>) => Promise<{
          content?: Array<{ type: string; text: string }>
          isError?: boolean
          message?: string
        }>)
      | undefined {
      // Determine which authentication methods are available
      const cdaOnlyHandlers = {
        // Only GraphQL operations are allowed with just a CDA token
        graphql_query: graphqlHandlers.executeQuery,
        graphql_list_content_types: graphqlHandlers.listContentTypes,
        graphql_get_content_type_schema: graphqlHandlers.getContentTypeSchema,
        graphql_get_example: graphqlHandlers.getExample,
      }
    
      // @ts-expect-error - The exact parameter and return types don't match, but they work at runtime
      return cdaOnlyHandlers[name as keyof typeof cdaOnlyHandlers]
    }
  • TypeScript interface defining input arguments for the GraphQL query handler.
    export interface GraphQLQueryArgs {
      spaceId?: string // Optional override for environment variable
      environmentId?: string // Optional override for environment variable
      query: string
      variables?: Record<string, any>
    }

Latest Blog Posts

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/ivo-toby/contentful-mcp-graphql'

If you have feedback or need assistance with the MCP directory API, please join our Discord server