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>
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It discloses that space ID and CDA token are automatically retrieved from environment variables (helpful for auth context), but doesn't mention rate limits, error handling, or what the response looks like. It adds some behavioral context but leaves significant gaps for a query execution tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with the most important information (prerequisites and core purpose). However, the middle sentence about 'powerful GraphQL interface' adds limited value and could be more concise. Overall efficient but with minor verbosity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a GraphQL query execution tool with 4 parameters, no annotations, and no output schema, the description provides good prerequisites and purpose but lacks details about response format, error cases, or authentication requirements beyond environment variables. It's adequate but has clear gaps given the tool's complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all 4 parameters thoroughly. The description doesn't add any meaningful parameter semantics beyond what's in the schema - it mentions environment variables for spaceId/environmentId but this is already covered in schema descriptions. Baseline 3 is appropriate when schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Execute a GraphQL query against the Contentful GraphQL API' and distinguishes it from REST API calls. However, it doesn't explicitly differentiate from sibling GraphQL tools like graphql_get_example, which might also execute queries.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage guidelines: it states that users MUST first use graphql_list_content_types and graphql_get_content_type_schema before using this tool, and explains when to use it (for flexible/efficient content retrieval vs REST). This directly addresses when and how to use this tool relative to alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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