Skip to main content
Glama
ivo-toby

Contentful GraphQL MCP Server

build_search_query

Generate GraphQL search queries for Contentful content types to find specific text across searchable fields, returning query strings and required variables.

Instructions

Generate a GraphQL search query for a specific content type based on cached schema information. Returns the query string and variables needed to search text fields in the content type.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentTypeYesThe content type to build a search query for
searchTermYesThe term to search for
fieldsNoOptional: Specific fields to search (default: all searchable text fields)
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 that builds a GraphQL search query for a given content type by identifying searchable text fields from the cached schema and constructing a query with OR conditions across those fields.
      buildSearchQuery: async (args: BuildSearchQueryArgs): Promise<ToolResponse> => {
        try {
          if (!isCacheAvailable()) {
            return {
              content: [
                {
                  type: "text",
                  text: "Query builder requires cached metadata. Please wait for the cache to load.",
                },
              ],
              isError: true,
            }
          }
    
          const schema = getCachedContentTypeSchema(args.contentType)
          if (!schema) {
            // Try with Collection suffix
            const collectionSchema = getCachedContentTypeSchema(`${args.contentType}Collection`)
            if (!collectionSchema) {
              return {
                content: [
                  {
                    type: "text",
                    text: `Content type "${args.contentType}" not found in cache. Use graphql_list_content_types to see available content types.`,
                  },
                ],
                isError: true,
              }
            }
          }
    
          const actualSchema = schema || getCachedContentTypeSchema(`${args.contentType}Collection`)
          const contentTypeName = actualSchema.contentType
    
          // Find the correct query name from cached content types
          const cachedContentTypes = getCachedContentTypes()
          const contentTypeInfo = cachedContentTypes?.find(
            (ct) =>
              ct.name === args.contentType ||
              ct.name === contentTypeName ||
              ct.queryName === contentTypeName,
          )
    
          const queryName =
            contentTypeInfo?.queryName ||
            (contentTypeName.endsWith("Collection") ? contentTypeName : `${contentTypeName}Collection`)
    
          // Determine which fields to search
          let fieldsToSearch = actualSchema.fields.filter((field: any) =>
            isSearchableTextField(field.type),
          )
    
          if (args.fields && args.fields.length > 0) {
            // Use only specified fields that are also searchable
            fieldsToSearch = fieldsToSearch.filter((field: any) => args.fields!.includes(field.name))
          }
    
          if (fieldsToSearch.length === 0) {
            return {
              content: [
                {
                  type: "text",
                  text: `No searchable text fields found for content type "${args.contentType}". Available fields: ${actualSchema.fields.map((f: any) => f.name).join(", ")}`,
                },
              ],
              isError: true,
            }
          }
    
          // Build search conditions
          const searchConditions = fieldsToSearch
            .map((field: any) => `{ ${field.name}_contains: $searchTerm }`)
            .join(", ")
    
          // Get all fields for selection (scalars only for simplicity)
          const scalarFields = actualSchema.fields
            .filter((field: any) => isScalarType(field.type))
            .map((field: any) => field.name)
    
          const query = `query Search${contentTypeName.replace("Collection", "")}($searchTerm: String!) {
      ${queryName}(where: { OR: [${searchConditions}] }, limit: 10) {
        items {
          sys { id }
    ${scalarFields.map((field: any) => `      ${field}`).join("\n")}
        }
      }
    }`
    
          return {
            content: [
              {
                type: "text",
                text: query,
              },
            ],
          }
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error building search query: ${error instanceof Error ? error.message : String(error)}`,
              },
            ],
            isError: true,
          }
        }
      },
  • Input schema definition for the build_search_query tool, specifying parameters like contentType, searchTerm, and optional fields.
    BUILD_SEARCH_QUERY: {
      name: "build_search_query",
      description:
        "Generate a GraphQL search query for a specific content type based on cached schema information. Returns the query string and variables needed to search text fields in the content type.",
      inputSchema: getOptionalEnvProperties({
        type: "object",
        properties: {
          contentType: {
            type: "string",
            description: "The content type to build a search query for",
          },
          searchTerm: {
            type: "string",
            description: "The term to search for",
          },
          fields: {
            type: "array",
            items: { type: "string" },
            description: "Optional: Specific fields to search (default: all searchable text fields)",
          },
        },
        required: ["contentType", "searchTerm"],
      }),
    },
  • src/index.ts:118-131 (registration)
    Registration of the build_search_query handler in the getHandler function which maps tool names to their handler functions.
    // 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]
    }
  • TypeScript interface defining the arguments for the buildSearchQuery handler.
    export interface BuildSearchQueryArgs {
      contentType: string
      searchTerm: string
      fields?: string[] // Optional specific fields to search
      spaceId?: string // Optional override for environment variable
      environmentId?: string // Optional override for environment variable
    }
  • src/index.ts:45-46 (registration)
    Inclusion of BUILD_SEARCH_QUERY in the static tools list returned by getAllTools() for MCP capabilities.
    if (allStaticTools.BUILD_SEARCH_QUERY)
      staticTools.BUILD_SEARCH_QUERY = allStaticTools.BUILD_SEARCH_QUERY
Behavior2/5

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

No annotations are provided, so the description must fully disclose behavioral traits. It mentions that the tool 'returns the query string and variables,' which adds some context about output format. However, it fails to describe critical behaviors: whether this is a read-only operation (likely, but not stated), if it requires specific permissions or authentication, potential rate limits, or how it handles errors (e.g., if cached schema is missing). For a tool with no annotations, this leaves significant gaps in transparency.

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 concise and front-loaded, with two sentences that directly state the tool's purpose and output. There is no wasted text, and it efficiently communicates key information. However, it could be slightly more structured by explicitly separating purpose from output details, but this is minor.

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 the tool's moderate complexity (5 parameters, no output schema, no annotations), the description is partially complete. It covers the basic purpose and output format but lacks details on behavioral aspects like error handling, dependencies on cached data, or comparison to siblings. Without annotations or output schema, more context on what the returned 'query string and variables' entail would be helpful, but the description is adequate for a minimal viable understanding.

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 input schema already documents all parameters thoroughly. The description adds minimal value beyond the schema: it implies that 'fields' defaults to 'all searchable text fields' and mentions 'cached schema information,' which provides some context for 'contentType.' However, it doesn't explain parameter interactions or provide examples, such as how 'spaceId' and 'environmentId' overrides work in practice. Baseline 3 is appropriate since the schema does most of the work.

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: 'Generate a GraphQL search query for a specific content type based on cached schema information.' It specifies the verb ('generate'), resource ('GraphQL search query'), and scope ('for a specific content type'), distinguishing it from siblings like 'graphql_query' (general querying) or 'smart_search' (likely higher-level search). However, it doesn't explicitly contrast with 'graphql_get_example' or 'graphql_list_content_types', leaving some sibling differentiation incomplete.

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

Usage Guidelines3/5

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

The description implies usage context by mentioning 'cached schema information' and 'search text fields in the content type,' suggesting it's for building queries when schema details are available. However, it lacks explicit guidance on when to use this tool versus alternatives like 'graphql_query' (for executing queries) or 'smart_search' (for automated searching), and doesn't specify prerequisites or exclusions, such as requiring cached schema data to be present.

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