Skip to main content
Glama
ctkadvisors

GraphQL MCP Server

by ctkadvisors

countries

Query country data with precision using GraphQL. Apply filters to retrieve specific information, enabling structured and efficient data access for your applications.

Instructions

GraphQL countries query

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filterNofilter - Input type: CountryFilterInput

Implementation Reference

  • Dynamically registers tools by fetching GraphQL schema and generating MCP tools from query fields, including 'countries' if present.
    if (method === "tools/list") {
      // Get schema (will use cache if available)
      const schema = await fetchSchema();
      const queryTools = getToolsFromSchema(schema);
      
      // Only include mutations if they are enabled
      const mutationTools = ENABLE_MUTATIONS ? getToolsFromMutationType(schema) : [];
      const allTools = [...queryTools, ...mutationTools];
    
      log(
        "info",
        `Returning ${allTools.length} tools (${queryTools.length} queries, ${mutationTools.length} mutations${!ENABLE_MUTATIONS ? ' - mutations disabled' : ''})`
      );
    
      const response: JSONRPCResponse = {
        jsonrpc: "2.0",
        id,
        result: {
          tools: allTools,
        },
      };
      console.log(JSON.stringify(response));
      return;
  • Executes the tool logic for query tools like 'countries': processes args, builds and runs GraphQL query against the countries endpoint.
    async function executeGraphQLTool(
      name: string,
      args: Record<string, any> | undefined
    ): Promise<any> {
      try {
        // If this name is in our mapping, use the original field name
        const actualFieldName = toolNameMappings[name] || name;
    
        // Check if the tool is in the whitelist (if whitelist is enabled)
        if (WHITELISTED_QUERIES && !WHITELISTED_QUERIES.includes(actualFieldName)) {
          throw new Error(`Tool '${actualFieldName}' is not in the whitelist`);
        }
    
        // Get the schema
        const schema = await fetchSchema();
        if (!schema) {
          throw new Error("Schema not available");
        }
    
        // Get the query type
        const queryType = schema.getQueryType();
        if (!queryType) {
          throw new Error("Schema has no query type");
        }
    
        // Get the field for this tool using the resolved field name
        const fields = queryType.getFields();
        const field = fields[actualFieldName];
    
        if (!field) {
          throw new Error(`Unknown field: ${actualFieldName}`);
        }
    
        try {
          // Process input arguments
          const processedArgs = processArguments(args, field.args, schema);
    
          // Get return type and analyze it
          const returnType = getNamedType(field.type);
    
          // First determine which arguments are actually being used
          const usedArgNames: string[] = [];
          field.args.forEach((arg) => {
            if (processedArgs && processedArgs[arg.name] !== undefined) {
              usedArgNames.push(arg.name);
            }
          });
    
          // Build variables definition - only for arguments that are actually used
          const varDefs = field.args
            .filter((arg) => usedArgNames.includes(arg.name))
            .map((arg) => {
              // Need to preserve non-null and list wrappers in variable definitions
              const typeStr = arg.type.toString();
              return `$${arg.name}: ${typeStr}`;
            })
            .filter(Boolean)
            .join(", ");
    
          // Build field arguments - only for arguments that are actually used
          const fieldArgs = usedArgNames
            .map((argName) => {
              return `${argName}: $${argName}`;
            })
            .join(", ");
    
          // Build selection set based on return type
          let selectionSet = "";
    
          if (isObjectType(returnType)) {
            // For objects or lists of objects, analyze fields
            const fields = analyzeFields(returnType, schema);
            selectionSet = buildSelectionSet(fields);
          } else if (isListType(returnType)) {
            // For lists, unwrap and analyze the inner type
            const innerType = getNamedType(returnType.ofType);
            if (isObjectType(innerType)) {
              const fields = analyzeFields(innerType as GraphQLObjectType, schema);
              selectionSet = buildSelectionSet(fields);
            }
          }
    
          // Build the final query
          // Only include variable definitions if fieldArgs is used
          const shouldIncludeVarDefs = fieldArgs && fieldArgs.length > 0;
          const query = `
            query ${name}Query${shouldIncludeVarDefs ? `(${varDefs})` : ""} {
              ${name}${fieldArgs && fieldArgs.length > 0 ? `(${fieldArgs})` : ""} ${
            selectionSet ? `{\n${selectionSet}  }` : ""
          }
            }
          `;
    
          log("debug", `Generated query for ${name}:`, {
            query,
            variables: processedArgs,
          });
    
          // Execute the query
          return await executeQuery({ query, variables: processedArgs });
        } catch (error) {
          throw new Error(
            `Error executing query for ${name}: ${
              error instanceof Error ? error.message : String(error)
            }`
          );
        }
      } catch (error) {
        log(
          "error",
          `Error executing tool ${name}: ${
            error instanceof Error ? error.message : String(error)
          }`
        );
        throw error;
      }
    }
  • Dynamically generates inputSchema for each query field turned into a tool, deriving JSON schema from GraphQL argument types.
    function getToolsFromSchema(schema: GraphQLSchema | null): MCPTool[] {
      if (!schema) {
        return []; // Return empty tools list if no schema available
      }
    
      const tools: MCPTool[] = [];
    
      // Get the query type from the schema
      const queryType = schema.getQueryType();
      if (!queryType) {
        log("warning", "Schema has no query type");
        return tools;
      }
    
      // Get all available query fields
      const fields = queryType.getFields();
    
      // Process each query field as a potential tool
      for (const [fieldName, field] of Object.entries(fields)) {
        // Skip fields that aren't in the whitelist (if a whitelist is provided)
        if (WHITELISTED_QUERIES && !WHITELISTED_QUERIES.includes(fieldName)) {
          if (DEBUG) {
            log("debug", `Skipping field ${fieldName} - not in whitelist`);
          }
          continue;
        }
        try {
          // Analyze arguments for the field
          const properties: Record<string, any> = {};
          const required: string[] = [];
    
          // Process arguments
          field.args.forEach((arg) => {
            // Get the actual GraphQL type (unwrap non-null and list types)
            let argType = arg.type;
            let isNonNull = false;
    
            if (isNonNullType(argType)) {
              isNonNull = true;
              argType = argType.ofType;
            }
    
            let isList = false;
            if (isListType(argType)) {
              isList = true;
              argType = argType.ofType;
              // Unwrap non-null inside list if needed
              if (isNonNullType(argType)) {
                argType = argType.ofType;
              }
            }
    
            const baseType = getNamedType(argType);
    
            // Create property definition
            if (isScalarType(baseType)) {
              // For scalar types like Int, String, etc.
              properties[arg.name] = {
                type: getJsonSchemaType(baseType.name),
                description:
                  arg.description || `${arg.name} parameter (${baseType.name})`,
              };
            } else if (isEnumType(baseType)) {
              // For enum types, specify allowed values
              const enumValues = baseType.getValues().map((val) => val.name);
              properties[arg.name] = {
                type: "string",
                enum: enumValues,
                description:
                  arg.description || `${arg.name} parameter (${baseType.name})`,
              };
            } else if (isInputObjectType(baseType)) {
              // For input object types (complex types), describe it as object
              properties[arg.name] = {
                type: "object",
                description: `${arg.name} - Input type: ${baseType.name}`,
              };
    
              // If we wanted to go deeper, we could recursively define the object structure:
              // properties[arg.name].properties = getInputObjectProperties(baseType);
            } else {
              // Default catch-all
              properties[arg.name] = {
                type: "string",
                description: arg.description || `${arg.name} parameter`,
              };
            }
    
            // If arg is non-null, add to required list
            if (isNonNull) {
              required.push(arg.name);
            }
          });
    
          // Create a tool for this field - Truncate name to 64 characters if needed
          const truncatedName =
            fieldName.length > 64 ? fieldName.substring(0, 64) : fieldName;
    
          // Store mapping from truncated to original name if truncation occurred
          if (truncatedName !== fieldName) {
            toolNameMappings[truncatedName] = fieldName;
          }
    
          const tool: MCPTool = {
            name: truncatedName,
            description: field.description || `GraphQL ${fieldName} query`,
            inputSchema: {
              type: "object",
              properties: properties,
              required: required,
            },
          };
    
          tools.push(tool);
        } catch (error) {
          log(
            "error",
            `Error processing field ${fieldName}: ${
              error instanceof Error ? error.message : String(error)
            }`
          );
        }
      }
    
      return tools;
    }
  • Default endpoint configuration for the countries GraphQL API used by all tools.
    const GRAPHQL_API_ENDPOINT: string =
      process.env.GRAPHQL_API_ENDPOINT ||
      "https://countries.trevorblades.com/graphql";
  • Fetches and caches the GraphQL schema from the countries endpoint to enable dynamic tool generation.
    async function fetchSchema(): Promise<GraphQLSchema | null> {
      // Prevent concurrent schema fetches
      if (schemaFetchInProgress) {
        log("info", "Schema fetch already in progress, waiting for it to complete");
        while (schemaFetchInProgress) {
          await new Promise((resolve) => setTimeout(resolve, 50));
        }
        return schemaCache;
      }
    
      // Check if we have a valid cached schema
      const now = Date.now();
      if (schemaCache && schemaCacheExpiry && now < schemaCacheExpiry) {
        log("info", "Using cached schema");
        return schemaCache;
      }
    
      try {
        schemaFetchInProgress = true;
        log("info", `Fetching GraphQL schema from ${GRAPHQL_API_ENDPOINT}`);
    
        // Build headers
        const headers: Record<string, string> = {};
        if (GRAPHQL_API_KEY) {
          headers.Authorization = `Bearer ${GRAPHQL_API_KEY}`;
        }
    
        // Create client and execute introspection query
        const client = new GraphQLClient(GRAPHQL_API_ENDPOINT, { headers });
        const startTime = Date.now();
        const data = await client.request<IntrospectionQuery>(
          getIntrospectionQuery()
        );
        const schema = buildClientSchema(data);
        const duration = Date.now() - startTime;
    
        log("info", `Schema fetched successfully in ${duration}ms`);
    
        // Cache the schema and reset the name mappings
        schemaCache = schema;
        schemaCacheExpiry = now + CACHE_TTL;
        toolNameMappings = {}; // Reset mappings as schema might have changed
    
        return schema;
      } catch (error) {
        log(
          "error",
          `Error fetching schema: ${
            error instanceof Error ? error.message : String(error)
          }`
        );
        return null;
      } finally {
        schemaFetchInProgress = false;
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It only states it's a 'GraphQL countries query', which implies a read operation but doesn't clarify if it's safe, what data it returns, or any constraints like rate limits or authentication needs. For a query tool with zero annotation coverage, this is a significant gap 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 very concise with 'GraphQL countries query', which is efficient and front-loaded. However, it's overly brief to the point of under-specification, lacking necessary details for clarity. It earns a high score for conciseness but loses points for not providing enough substance to be truly helpful.

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

Completeness2/5

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

Given the complexity (1 parameter with nested object, no output schema, no annotations), the description is incomplete. It doesn't explain what the tool returns, how to use the filter, or differentiate from siblings. For a query tool with these contextual signals, more detail is needed to be considered adequately complete.

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%, with the schema documenting the 'filter' parameter as an object of type 'CountryFilterInput'. The description adds no additional meaning beyond this, such as examples of filter criteria or usage context. With high schema coverage, the baseline score of 3 is appropriate, as the schema does the heavy lifting for parameter documentation.

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

Purpose2/5

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

The description 'GraphQL countries query' restates the tool name 'countries' and adds only the generic term 'GraphQL query', which is tautological. It doesn't specify what the query actually does (e.g., retrieve, list, search countries) or distinguish it from sibling tools like 'country' (singular) or 'continent' tools. The purpose remains vague beyond being a GraphQL operation.

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

Usage Guidelines1/5

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

There is no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'country' (likely for a single country) or 'continents', nor does it provide any context for usage scenarios (e.g., filtering, listing all countries). The description lacks any indication of prerequisites or exclusions.

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

Related 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/ctkadvisors/graphql-mcp'

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