Skip to main content
Glama
ivo-toby

Contentful GraphQL MCP Server

graphql_get_example

Generate example GraphQL queries for specific Contentful content types to help construct valid queries after reviewing the schema.

Instructions

IMPORTANT: Use this tool AFTER using graphql_get_content_type_schema to see example GraphQL queries for a specific content type. Learning from these examples will help you construct valid queries. The space ID and CDA token are automatically retrieved from environment variables.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentTypeYesThe name of the content type for the example query
includeRelationsNoWhether to include related content types in the example (defaults to false)
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

  • The handler function `getExample` that generates and returns example GraphQL queries for a specified content type based on its schema.
      getExample: async (args: GetGraphQLExampleArgs): 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"
    
          // First get the schema
          const schemaResult = await graphqlHandlers.getContentTypeSchema({
            contentType: args.contentType,
            spaceId,
            environmentId,
          })
    
          if (schemaResult.isError) {
            return schemaResult
          }
    
          // Parse the schema from the result
          const schemaData = JSON.parse(schemaResult.content[0].text)
    
          // Generate a query for collection
          const isCollection = schemaData.contentType.endsWith("Collection")
          const contentTypeName = isCollection
            ? schemaData.contentType
            : schemaData.contentType.replace(/^[A-Z]/, (c: string) => c.toLowerCase())
          const collectionName = isCollection ? contentTypeName : `${contentTypeName}Collection`
          const singularName = isCollection
            ? contentTypeName.replace("Collection", "")
            : contentTypeName
    
          // Get top-level scalar fields
          const scalarFields = schemaData.fields
            .filter((field: any) => isScalarType(field.type))
            .map((field: any) => field.name)
    
          // Get reference fields if requested
          const referenceFields = args.includeRelations
            ? schemaData.fields
                .filter((field: any) => isReferenceType(field.type))
                .map((field: any) => ({
                  name: field.name,
                  type: field.type.replace("!", ""),
                }))
            : []
    
          // Build the example query
          let exampleQuery = `# Example query for ${schemaData.contentType}
    query {
      ${collectionName}(limit: 5) {
        items {
    ${scalarFields.map((field: string) => `      ${field}`).join("\n")}`
    
          if (referenceFields.length > 0) {
            exampleQuery += `\n
          # Related content references
    ${referenceFields
      .map(
        (field: any) => `      ${field.name} {
            ... on ${field.type} {
              # Add fields you want from ${field.type} here
            }
          }`,
      )
      .join("\n")}`
          }
    
          exampleQuery += `\n    }
      }
    }
    
    # You can also query a single item by ID
    query GetSingle${singularName}($id: String!) {
      ${singularName}(id: $id) {
    ${scalarFields.map((field: string) => `    ${field}`).join("\n")}
      }
    }
    
    # Variables for the above query would be:
    # {
    #   "id": "your-entry-id-here"
    # }`
    
          return {
            content: [
              {
                type: "text",
                text: exampleQuery,
              },
            ],
          }
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error generating example query: ${error instanceof Error ? error.message : String(error)}`,
              },
            ],
            isError: true,
          }
        }
      },
  • The tool schema definition for 'graphql_get_example', including input schema with properties like contentType and includeRelations.
    GRAPHQL_GET_EXAMPLE: {
      name: "graphql_get_example",
      description:
        "IMPORTANT: Use this tool AFTER using graphql_get_content_type_schema to see example GraphQL queries for a specific content type. Learning from these examples will help you construct valid queries. The space ID and CDA token are automatically retrieved from environment variables.",
      inputSchema: getOptionalEnvProperties({
        type: "object",
        properties: {
          contentType: {
            type: "string",
            description: "The name of the content type for the example query",
          },
          includeRelations: {
            type: "boolean",
            description:
              "Whether to include related content types in the example (defaults to false)",
          },
        },
        required: ["contentType"],
      }),
    },
  • src/index.ts:118-131 (registration)
    Registration of the tool name 'graphql_get_example' to the handler graphqlHandlers.getExample in the main server 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 the tool name 'graphql_get_example' to the handler in the StreamableHTTP transport'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 the input arguments for the getExample handler.
    export interface GetGraphQLExampleArgs {
      contentType: string
      includeRelations?: boolean
      spaceId?: string // Optional override for environment variable
      environmentId?: string // Optional override for environment variable
    }
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 of behavioral disclosure. It mentions that space ID and CDA token are automatically retrieved from environment variables, which adds useful context about authentication and defaults. However, it lacks details on rate limits, error handling, or what the output looks like (e.g., format of examples), leaving gaps in behavioral understanding.

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 with three sentences that each serve a purpose: stating the tool's function, providing usage context, and explaining authentication. It's front-loaded with the key purpose. However, the second sentence could be slightly more concise, and there's minor redundancy in explaining environment variables.

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?

Given no annotations and no output schema, the description is moderately complete. It covers the tool's purpose, prerequisites, and authentication context, but lacks details on output format, error cases, or performance considerations. For a tool with 4 parameters and no structured output documentation, this leaves room for improvement in guiding the agent fully.

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 four parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema (e.g., it doesn't explain 'contentType' further or provide examples of valid values). This meets the baseline for high schema coverage but doesn't enhance parameter understanding.

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: to retrieve example GraphQL queries for a specific content type after using another tool. It specifies the verb 'see example GraphQL queries' and resource 'for a specific content type', making the function unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'graphql_query' or 'smart_search', which prevents a perfect score.

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 guidance: it states to use this tool AFTER using 'graphql_get_content_type_schema' and that learning from examples helps construct valid queries. This clearly defines when to use it (after schema retrieval) and implies an alternative (constructing queries manually without examples), though it doesn't explicitly name all sibling 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