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
| Name | Required | Description | Default |
|---|---|---|---|
| filter | No | filter - Input type: CountryFilterInput |
Implementation Reference
- src/graphql-mcp-server.ts:1055-1077 (registration)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;
- src/graphql-mcp-server.ts:729-845 (handler)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; } }
- src/graphql-mcp-server.ts:296-421 (schema)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; }
- src/graphql-mcp-server.ts:87-89 (helper)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";
- src/graphql-mcp-server.ts:227-282 (helper)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; } }