gqlt

package module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2025 License: MIT Imports: 24 Imported by: 0

README

gqlt

A triple-threat GraphQL tool: CLI client, MCP server, and Go library.

Overview

gqlt operates in three distinct modes:

1. CLI Mode: Composable Unix Tool

A minimal command-line client for running GraphQL operations that follows Unix philosophy:

  • Accepts input from stdin, files, or arguments
  • Outputs structured data (JSON/YAML/table) to stdout
  • Composes with other Unix tools via pipes (jq, grep, awk, etc.)
  • Supports queries, mutations, subscriptions, and introspection
2. MCP Mode: AI Agent Server

A Model Context Protocol (MCP) server that provides GraphQL capabilities to AI agents:

  • Execute queries against any GraphQL endpoint
  • Introspect and explore GraphQL schemas
  • List and describe types with intelligent filtering
  • Check version information
  • Integrates with Cursor, Claude Desktop, and other MCP-compatible tools
3. Library Mode: Go Package

A clean, testable Go library for GraphQL operations in your own applications:

  • Pure functions with no side effects (import "github.com/kluzzebass/gqlt")
  • Embed GraphQL client in your Go applications
  • Perfect for testing GraphQL integrations
  • Comprehensive API with full type safety
  • Mock server infrastructure included (gqlt/internal/testutil)
Quick Start

CLI Usage:

# Basic query execution
gqlt run --url https://api.example.com/graphql --query "{ users { id name } }"

# Compose with jq to extract data
gqlt run --query "{ users { id name email } }" --format json --quiet | \
  jq '.data.users[] | select(.email | contains("@example.com"))'

# Using configuration
gqlt config create production
gqlt config set production endpoint https://api.example.com/graphql
gqlt run --query "{ users { id name } }"

# Check version
gqlt version

# GraphQL subscriptions (WebSocket)
gqlt run --url wss://api.example.com/graphql --query 'subscription { events { id type data } }'

# Limit subscription messages
gqlt run --url wss://api.example.com/graphql \
  --query 'subscription { updates }' \
  --max-messages 10 \
  --timeout 30s

Mock Server Usage:

# Start comprehensive mock GraphQL server for testing
gqlt serve

# Custom address
gqlt serve --listen :3000

# Test against the mock server
gqlt serve &
gqlt run --url http://localhost:8090/graphql --query '{ users { id name email role } }'
gqlt run --url http://localhost:8090/graphql --query 'subscription { counter }' --timeout 5s

MCP Server Usage:

# Start MCP server for AI agents
gqlt mcp

Add to Cursor's mcp.json or Claude Desktop config:

{
  "mcpServers": {
    "gqlt": {
      "command": "gqlt",
      "args": ["mcp"]
    }
  }
}

Library Usage:

import "github.com/kluzzebass/gqlt"

// Create client and execute query
client := gqlt.NewClient("https://api.example.com/graphql", nil)
response, err := client.Execute(`query { users { id name } }`, nil, "")

// Use mock server for testing
import "github.com/kluzzebass/gqlt/internal/testutil"

mockServer := testutil.NewMockGraphQLServer()
defer mockServer.Close()
mockServer.AddHandler("GetUsers", func(req testutil.Request) *gqlt.Response {
    return testutil.SuccessResponse(map[string]interface{}{
        "users": []map[string]interface{}{{"id": "1", "name": "Test User"}},
    })
})

Installation

CLI Binary

From Source:

git clone https://github.com/kluzzebass/gqlt.git
cd gqlt
go build -o gqlt ./cmd

From Releases: Download the latest release for your platform from the releases page.

Go Library
go get github.com/kluzzebass/gqlt

The Trinity: Three Tools in One

Mode 1: Composable CLI

The CLI mode outputs clean, structured data that composes naturally with Unix tools:

# Extract and filter user emails
gqlt run --query "{ users { id name email } }" --format json --quiet | \
  jq -r '.data.users[] | select(.email | contains("@example.com")) | .email'

# Count total types in a schema
gqlt introspect --format json --quiet | jq '.data.__schema.types | length'

# Find types matching a pattern
gqlt introspect --format json --quiet | \
  jq -r '.data.__schema.types[].name' | grep -i "user"

# Chain multiple queries
user_id=$(gqlt run --query "{ users { id } }" --format json --quiet | jq -r '.data.users[0].id')
gqlt run --query "query(\$id: ID!) { user(id: \$id) { name email } }" \
  --vars "{\"id\": \"$user_id\"}" --format json --quiet

# GraphQL subscriptions (streamed output)
gqlt run --url wss://api.example.com/graphql \
  --query 'subscription { events { id type data } }' | jq .

# Limit subscription duration and message count
gqlt run --url wss://api.example.com/graphql \
  --query 'subscription { updates }' \
  --max-messages 10 --timeout 1m | jq -c '.data.updates'
Mode 2: MCP Server for AI Agents

Run as a server to provide GraphQL capabilities to AI agents:

# Start the MCP server (stdin/stdout mode)
gqlt mcp

Integration with Cursor:

Add to your ~/.cursor/mcp.json or workspace .cursor/mcp.json:

{
  "mcpServers": {
    "gqlt": {
      "command": "gqlt",
      "args": ["mcp"],
      "env": {}
    }
  }
}

Integration with Claude Desktop:

Add to ~/.config/claude-desktop/config.json (macOS/Linux) or %APPDATA%\Claude\config.json (Windows):

{
  "mcpServers": {
    "gqlt": {
      "command": "/usr/local/bin/gqlt",
      "args": ["mcp"],
      "env": {}
    }
  }
}

Available MCP Tools:

  • execute_query: Run GraphQL queries, mutations, and subscriptions (supports file uploads)
  • describe_type: Analyze specific GraphQL types with detailed field information
  • list_types: List and filter GraphQL type names (supports regex patterns and kind filtering)
  • version: Get the current version of gqlt

File Upload Support: The execute_query tool supports file uploads for mutations with Upload scalar types. Provide local file paths:

{
  "query": "mutation($file: Upload!) { uploadFile(file: $file) { id url } }",
  "variables": {"file": null},
  "endpoint": "https://api.example.com/graphql",
  "files": {
    "file": "/Users/you/photos/avatar.jpg"
  }
}

Subscription Support: The execute_query tool supports GraphQL subscriptions via WebSocket. Use timeout and maxMessages to control execution:

{
  "query": "subscription { events { id type data } }",
  "endpoint": "wss://api.example.com/graphql",
  "timeout": "30s",
  "maxMessages": 10
}

Subscriptions will:

  • Automatically convert https:// URLs to wss:// and http:// to ws://
  • Stream messages until timeout, maxMessages limit, or Cursor cancellation
  • Return each message as a complete GraphQL response
  • Clean up WebSocket connection on completion or error

Tool Parameters:

  • Schema-related tools (describe_type and list_types) support noCache parameter to force fresh schema introspection
  • execute_query supports files parameter for file uploads via local filesystem paths
Mode 3: Go Library

Use gqlt as a library in your own Go applications:

package main

import (
    "fmt"
    "github.com/kluzzebass/gqlt"
)

func main() {
    // Create a GraphQL client
    client := gqlt.NewClient("https://api.example.com/graphql", nil)
    
    // Set authentication
    client.SetHeaders(map[string]string{
        "Authorization": "Bearer your-token",
    })
    
    // Execute a query
    response, err := client.Execute(
        `query GetUsers { users { id name email } }`,
        nil,
        "GetUsers",
    )
    
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Response: %+v\n", response.Data)
}

Testing with Mock Server:

package yourpackage_test

import (
    "testing"
    "github.com/kluzzebass/gqlt"
    "github.com/kluzzebass/gqlt/internal/testutil"
)

func TestYourGraphQLIntegration(t *testing.T) {
    // Create mock GraphQL server
    mockServer := testutil.NewMockGraphQLServer()
    defer mockServer.Close()
    
    // Configure mock responses
    mockServer.AddHandler("GetUser", func(req testutil.Request) *gqlt.Response {
        userID := req.Variables["id"].(string)
        return testutil.SuccessResponse(map[string]interface{}{
            "user": map[string]interface{}{
                "id":   userID,
                "name": "Test User",
                "email": "test@example.com",
            },
        })
    })
    
    // Use the mock server in your tests
    client := gqlt.NewClient(mockServer.URL(), nil)
    response, err := client.Execute(
        `query GetUser($id: ID!) { user(id: $id) { id name email } }`,
        map[string]interface{}{"id": "123"},
        "GetUser",
    )
    
    if err != nil {
        t.Fatalf("Query failed: %v", err)
    }
    
    // Validate response
    data := response.Data.(map[string]interface{})
    user := data["user"].(map[string]interface{})
    
    if user["id"] != "123" {
        t.Errorf("Expected user id 123, got %v", user["id"])
    }
}

Mock GraphQL Server

gqlt includes a comprehensive mock GraphQL server powered by gqlgen for testing and development:

Features
  • Complete Schema: Todo-list application with users, todos, attachments, and search
  • All GraphQL Features: Queries, mutations, subscriptions, unions, interfaces, custom scalars, directives
  • Relay Node Pattern: Global object identification with node(id: "Type:ID") queries
  • Real-Time Subscriptions: WebSocket and SSE support with event broadcasting
  • File Uploads: Multipart form-data for testing file upload mutations
  • Pre-Seeded Data: 3 sample users ready to use immediately
  • Introspection Enabled: Full schema introspection for tooling
Quick Start
# Start mock server (default: localhost:8090)
gqlt serve

# Custom address
gqlt serve --listen :3000
gqlt serve --listen 0.0.0.0:8080

# Without GraphQL Playground
gqlt serve --no-playground
Example Usage
# Start server in background
gqlt serve &

# Query pre-seeded users
gqlt run --url http://localhost:8090/graphql \
  --query '{ users { id name email role } }'

# Create a todo
gqlt run --url http://localhost:8090/graphql \
  --query 'mutation { createTodo(input: { title: "Test Todo" }) { id title status } }'

# Subscribe to real-time todo events
gqlt run --url http://localhost:8090/graphql \
  --query 'subscription { todoEvents { id title status } }' \
  --timeout 30s &

# Trigger events by creating todos
gqlt run --url http://localhost:8090/graphql \
  --query 'mutation { createTodo(input: { title: "Event Test" }) { id } }'

# Search across users and todos (union types)
gqlt run --url http://localhost:8090/graphql \
  --query '{ search(term: "admin") { ... on User { id name } ... on Todo { id title } } }'

# Test Relay Node pattern
gqlt run --url http://localhost:8090/graphql \
  --query '{ node(id: "User:1") { id ... on User { name email } } }'
Schema Highlights
  • Queries: hello, echo, user, users, todo, todos, search, currentTime, version, node
  • Mutations: createUser, createTodo, updateTodo, deleteTodo, completeTodo, addFileAttachment, addLinkAttachment, removeAttachment
  • Subscriptions: counter, todoEvents, userEvents, tick
  • Types: User, Todo, FileAttachment, LinkAttachment (with Node interface)
  • Unions: SearchResult (User | Todo | Post | Product | Service)
  • Enums: UserRole, TodoStatus, TodoPriority
  • Custom Scalars: DateTime, URL, Upload

Access the GraphQL Playground at http://localhost:8090/ to explore the complete schema interactively.

Documentation

Completion

Generate the autocompletion script for the specified shell

Synopsis

Generate the autocompletion script for gqlt for the specified shell. See each sub-command's help for details on how to use the generated script.

Options
  -h, --help   help for completion
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Completion Bash

Generate the autocompletion script for bash

Synopsis

Generate the autocompletion script for the bash shell.

This script depends on the 'bash-completion' package. If it is not installed already, you can install it via your OS's package manager.

To load completions in your current shell session:

source <(gqlt completion bash)

To load completions for every new session, execute once:

Linux:
gqlt completion bash > /etc/bash_completion.d/gqlt
macOS:
gqlt completion bash > $(brew --prefix)/etc/bash_completion.d/gqlt

You will need to start a new shell for this setup to take effect.

gqlt completion bash
Options
  -h, --help              help for bash
      --no-descriptions   disable completion descriptions
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Completion Fish

Generate the autocompletion script for fish

Synopsis

Generate the autocompletion script for the fish shell.

To load completions in your current shell session:

gqlt completion fish | source

To load completions for every new session, execute once:

gqlt completion fish > ~/.config/fish/completions/gqlt.fish

You will need to start a new shell for this setup to take effect.

gqlt completion fish [flags]
Options
  -h, --help              help for fish
      --no-descriptions   disable completion descriptions
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Completion Powershell

Generate the autocompletion script for powershell

Synopsis

Generate the autocompletion script for powershell.

To load completions in your current shell session:

gqlt completion powershell | Out-String | Invoke-Expression

To load completions for every new session, add the output of the above command to your powershell profile.

gqlt completion powershell [flags]
Options
  -h, --help              help for powershell
      --no-descriptions   disable completion descriptions
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Completion Zsh

Generate the autocompletion script for zsh

Synopsis

Generate the autocompletion script for the zsh shell.

If shell completion is not already enabled in your environment you will need to enable it. You can execute the following once:

echo "autoload -U compinit; compinit" >> ~/.zshrc

To load completions in your current shell session:

source <(gqlt completion zsh)

To load completions for every new session, execute once:

Linux:
gqlt completion zsh > "${fpath[1]}/_gqlt"
macOS:
gqlt completion zsh > $(brew --prefix)/share/zsh/site-functions/_gqlt

You will need to start a new shell for this setup to take effect.

gqlt completion zsh [flags]
Options
  -h, --help              help for zsh
      --no-descriptions   disable completion descriptions
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config

Manage gqlt configuration files

Synopsis

Manage gqlt configuration files with support for multiple named configurations. This allows you to store different settings for different environments (production, staging, local, etc.).

AI-FRIENDLY FEATURES:

  • Structured output with --format json|table|yaml
  • Machine-readable error codes
  • Quiet mode for automation
Examples
# Initialize and setup
gqlt config init
gqlt config create production
gqlt config set production endpoint https://api.prod.com/graphql
gqlt config set production headers '{"Authorization": "Bearer token"}'
gqlt config use production

# Environment management
gqlt config create staging
gqlt config set staging endpoint https://api.staging.com/graphql
gqlt config create local
gqlt config set local endpoint http://localhost:4000/graphql

# Configuration inspection
gqlt config list --format table
gqlt config show production --format json
gqlt config validate

# With authentication
gqlt config set myapi auth.token "your-bearer-token"
gqlt config set myapi auth.username "username"
gqlt config set myapi auth.password "password"
gqlt config set myapi auth.api_key "api-key"

# Clone configuration
gqlt config clone production staging

# Structured output for AI agents
gqlt config list --format json --quiet
gqlt config show --format yaml
Options
  -h, --help   help for config
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Clone

Clone an existing configuration

Synopsis

Create a new configuration by copying an existing one.

gqlt config clone <source> <target> [flags]
Options
  -h, --help   help for clone
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Create

Create a new configuration

Synopsis

Create a new named configuration with default values.

gqlt config create <name> [flags]
Examples
gqlt config create production
gqlt config create staging
gqlt config create local
Options
  -h, --help   help for create
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Delete

Delete a configuration

Synopsis

Delete a named configuration (cannot delete default).

gqlt config delete <name> [flags]
Options
  -h, --help   help for delete
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Init

Initialize configuration file

Synopsis

Create a new configuration file with default settings.

gqlt config init [flags]
Examples
gqlt config init
Options
  -h, --help   help for init
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config List

List all configurations

Synopsis

List all available configurations with their current status.

gqlt config list [flags]
Options
  -h, --help   help for list
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Set

Set a configuration value

Synopsis

Set a configuration value for a named configuration.

Available keys: endpoint - GraphQL endpoint URL (required) headers. - Custom HTTP header (e.g., headers.X-Custom "value") headers.Authorization - Authorization header (e.g., "Bearer token") headers.X-API-Key - API key header auth.token - Bearer token for authentication auth.username - Username for basic authentication auth.password - Password for basic authentication auth.api_key - API key for authentication defaults.out - Default output mode (json|pretty|raw)

Authentication precedence:

  1. Basic auth (auth.username + auth.password)
  2. Bearer token (auth.token)
  3. API key (auth.api_key)
  4. Custom headers (headers.Authorization, headers.X-API-Key)
gqlt config set <name> <key> <value> [flags]
Examples
# Basic configuration
gqlt config set production endpoint https://api.example.com/graphql
gqlt config set production defaults.out pretty

# Authentication methods
gqlt config set production auth.token "your-bearer-token"
gqlt config set production auth.username "admin"
gqlt config set production auth.password "secret"
gqlt config set production auth.api_key "api-key-123"

# Custom headers
gqlt config set production headers.X-Custom "custom-value"
gqlt config set production headers.Authorization "Bearer manual-token"
gqlt config set production headers.X-API-Key "manual-api-key"
Options
  -h, --help   help for set
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Show

Show current or named configuration

Synopsis

Show the current configuration or a specific named configuration.

gqlt config show [name] [flags]
Options
  -h, --help   help for show
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Use

Switch to a configuration

Synopsis

Switch the current active configuration to the specified name.

gqlt config use <name> [flags]
Options
  -h, --help   help for use
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Config Validate

Validate configuration

Synopsis

Check the configuration file for errors and provide suggestions.

gqlt config validate [flags]
Options
  -h, --help   help for validate
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Describe

Describe GraphQL types and fields from cached schema

Synopsis

Describe GraphQL types and fields from a cached schema file. Use this to explore the GraphQL schema structure.

gqlt describe [type|field] [flags]
Examples
# Describe a type
gqlt describe User

# Describe a field
gqlt describe Query.users

# Describe with JSON output
gqlt describe User --json

# Show summary only
gqlt describe User --summary
Options
  -h, --help            help for describe
      --json            output exact node JSON
      --schema string   schema file path (default is OS-specific)
      --summary         output plain text summary
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Docs

Generate documentation

Synopsis

Generate documentation in various formats from the command structure

gqlt docs [flags]
Examples
# Generate README.md
gqlt docs --format md --output README.md

# Generate man pages
gqlt docs --format man --output man/

# Generate multiple markdown files
gqlt docs --format md --tree --output docs/

# Output to stdout
gqlt docs --format md --output -
Options
  -f, --format string   Output format: md or man (default "md")
  -h, --help            help for docs
  -o, --output string   Output destination (file for md, directory for man, '-' for stdout) (default "-")
      --tree            Generate multiple files (one per command) instead of single file
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Introspect

Fetch and cache GraphQL schema via introspection

Synopsis

Fetch the GraphQL schema from an endpoint using introspection and save it to a local cache file for use with other commands.

gqlt introspect [flags]
Examples
# Fetch schema from URL
gqlt introspect --url https://api.example.com/graphql

# Fetch schema with authentication
gqlt introspect --url https://api.example.com/graphql --token "bearer-token"

# Force refresh cached schema
gqlt introspect --refresh

# Show schema summary
gqlt introspect --summary

# Save to specific file
gqlt introspect --output schema.json
Options
  -h, --help         help for introspect
      --out string   output file path (default is OS-specific)
      --refresh      ignore cache and fetch fresh schema
      --summary      show summary instead of saving to file
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Mcp

Start MCP (Model Context Protocol) server for AI agent integration

Synopsis

Start an MCP server that provides GraphQL query execution and schema exploration to AI agents via JSON-RPC 2.0. This allows AI agents to execute GraphQL queries, introspect schemas, and explore types through a standardized protocol using stdin/stdout communication.

The MCP server provides tools for:

  • execute_query: Run GraphQL queries, mutations, and subscriptions (supports file uploads via local paths)
  • describe_type: Analyze specific GraphQL types and fields with detailed information
  • list_types: List GraphQL type names with optional regex filtering
  • version: Get the current version of gqlt
gqlt mcp [flags]
Examples
# Start MCP server (stdin/stdout mode)
gqlt mcp

# For Cursor integration, add to mcp.json:
{
  "mcpServers": {
    "gqlt": {
      "command": "gqlt",
      "args": ["mcp"],
      "env": {}
    }
  }
}

# For Claude Desktop, add to ~/.config/claude-desktop/config.json:
{
  "mcpServers": {
    "gqlt": {
      "command": "gqlt",
      "args": ["mcp"],
      "env": {}
    }
  }
}
Options
  -h, --help   help for mcp
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Run

Execute a GraphQL operation against an endpoint

Synopsis

Execute a GraphQL operation (query or mutation) against a GraphQL endpoint. You can provide the query inline, from a file, or via stdin.

gqlt run [flags]
Examples
# Basic query
gqlt run --url https://api.example.com/graphql --query "{ users { id name } }"

# Query with variables
gqlt run --url https://api.example.com/graphql --query "query($id: ID!) { user(id: $id) { name } }" --vars '{"id": "123"}'

# Query from stdin
echo "{ users { id name } }" | gqlt run --url https://api.example.com/graphql

# Mutation with file upload
gqlt run --url https://api.example.com/graphql --query "mutation($file: Upload!) { uploadFile(file: $file) }" --file avatar=./photo.jpg

# Using configuration
gqlt run --query "{ users { id name } }"  # Uses configured endpoint

# Authentication (precedence: Basic Auth > Bearer Token > API Key)
gqlt run --username user --password pass --query "{ me { id } }"  # Basic auth (highest precedence)
gqlt run --token "bearer-token" --query "{ me { id } }"          # Bearer token
gqlt run --api-key "api-key" --query "{ me { id } }"             # API key (lowest precedence)

# Structured output for AI agents
gqlt run --format json --quiet --query "{ users { id } }"

# Multiple file uploads
gqlt run --query "mutation($files: [Upload!]!) { uploadFiles(files: $files) }" --files-list files.txt
Options
  -k, --api-key string       API key for authentication (sets X-API-Key header)
  -f, --file stringArray     File upload (name=path, repeatable, e.g. avatar=./photo.jpg)
  -F, --files-list string    File containing list of files to upload (one per line, format: name=path, supports # comments, ~ expansion, and relative paths)
  -H, --header stringArray   HTTP header (key=value, repeatable)
  -h, --help                 help for run
      --max-messages int     Maximum subscription messages to receive (0 = unlimited)
  -o, --operation string     Operation name
  -p, --password string      Password for basic authentication
  -q, --query string         Inline GraphQL document
  -Q, --query-file string    Path to .graphql file
      --timeout string       Subscription timeout (e.g. 30s, 5m)
  -t, --token string         Bearer token for authentication
  -u, --url string           GraphQL endpoint URL (required if not in config)
  -U, --username string      Username for basic authentication
  -v, --vars string          JSON object with variables
  -V, --vars-file string     Path to JSON file with variables
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Serve

Start a mock GraphQL server for testing

Synopsis

Start a mock GraphQL server with a comprehensive todo-list schema.

The server includes:

  • Queries: users, todos, search, and more
  • Mutations: create/update/delete users and todos
  • Subscriptions: real-time events for todos and users
  • File uploads via multipart/form-data
  • WebSocket and SSE transport for subscriptions
  • GraphQL Playground for interactive testing
  • Relay Node pattern for global object identification

The server is pre-seeded with sample data and ready to use immediately.

gqlt serve [flags]
Examples
  # Start server on default address (localhost:8090)
  gqlt serve

  # Start on custom port (binds to all interfaces, IPv6 with IPv4 fallback)
  gqlt serve --listen :3000

  # Start on all IPv4 interfaces
  gqlt serve --listen 0.0.0.0:3000

  # Start on localhost only (IPv4)
  gqlt serve --listen 127.0.0.1:3000

  # Start without playground
  gqlt serve --no-playground

  # Test with queries
  gqlt serve &
  gqlt run --url http://localhost:8090/graphql --query '{ users { id name email } }'
  
  # Test subscriptions
  gqlt serve &
  gqlt run --url http://localhost:8090/graphql --query 'subscription { counter }' --timeout 10s
Options
  -h, --help            help for serve
  -l, --listen string   Address to listen on (host:port) (default "localhost:8090")
      --playground      Enable GraphQL Playground (default true)
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Validate

Validate GraphQL queries, schemas, and configurations

Synopsis

Validate GraphQL queries, schemas, and configurations. This command provides structured validation results for AI agents and automation.

AI-FRIENDLY FEATURES:

  • Structured JSON output with validation results
  • Machine-readable error codes
  • Detailed validation information
  • Quiet mode for automation
Examples
# Validate a query against a schema
gqlt validate query --query "{ users { id name } }" --url https://api.example.com/graphql

# Validate query from file
gqlt validate query --query-file query.graphql --url https://api.example.com/graphql

# Validate configuration
gqlt validate config

# Validate schema
gqlt validate schema --url https://api.example.com/graphql

# Structured output for AI agents
gqlt validate query --query "{ users { id } }" --format json --quiet
Options
  -h, --help   help for validate
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Validate Config

Validate configuration files

Synopsis

Validate configuration files for syntax and completeness. Returns structured validation results with detailed error information.

gqlt validate config [flags]
Examples
gqlt validate config
gqlt validate config --format json --quiet
Options
  -h, --help   help for config
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Validate Query

Validate a GraphQL query against a schema

Synopsis

Validate a GraphQL query against a schema. Returns structured validation results including syntax errors, type errors, and field availability.

gqlt validate query [flags]
Examples
gqlt validate query --query "{ users { id name } }" --url https://api.example.com/graphql
gqlt validate query --query-file query.graphql --url https://api.example.com/graphql
gqlt validate query --query "{ users { id } }" --format json --quiet
Options
  -h, --help                help for query
  -q, --query string        GraphQL query to validate
  -Q, --query-file string   Path to GraphQL query file
  -u, --url string          GraphQL endpoint URL
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Validate Schema

Validate a GraphQL schema

Synopsis

Validate a GraphQL schema for correctness and completeness. Returns structured validation results with schema analysis.

gqlt validate schema [flags]
Examples
gqlt validate schema --url https://api.example.com/graphql
gqlt validate schema --url https://api.example.com/graphql --format json --quiet
Options
  -h, --help         help for schema
  -u, --url string   GraphQL endpoint URL
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Version

Display the current version of gqlt

Synopsis

Display the current version of gqlt.

gqlt version [flags]
Examples
# Show version
gqlt version

# Use in scripts
VERSION=$(gqlt version)
echo "Using gqlt version: $VERSION"
Options
  -h, --help   help for version
Options inherited from parent commands
      --config-dir string   config directory (default is OS-specific)
      --format string       Output format: json|table|yaml (default: json) (default "json")
      --quiet               Quiet mode - suppress non-essential output for automation
      --use-config string   use specific configuration by name (overrides current selection)

Limitations

gqlt is designed to be a focused, composable tool. The following are intentional limitations:

GraphQL Subscriptions:

  • Full WebSocket subscription support via graphql-transport-ws protocol
  • CLI: Streams messages to stdout (one JSON per line) until Ctrl+C or completion
  • MCP: Collects messages with timeout/max-messages limits, respects Cancel button
  • Library: Channel-based API for testing subscriptions
  • Auto-detects subscription operations and routes to WebSocket
  • Works with mixed operation documents (queries + mutations + subscriptions)

Response Filtering:

  • gqlt outputs raw GraphQL responses without built-in filtering
  • This is intentional - filtering should be done with specialized tools like jq
  • Example: gqlt run ... | jq '.data.users[] | select(.active)'
  • Follows Unix philosophy: do one thing well, compose with other tools

Schema Features:

  • SDL fallback supports standard GraphQL schemas
  • Some server-specific features may not be fully represented in introspection format
  • Custom scalars are preserved but not validated beyond GraphQL spec

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.


This documentation is auto-generated from the command structure. Last updated: $(date)

Documentation

Index

Constants

View Source
const (
	// Configuration errors
	ErrorCodeConfigLoad     = "CONFIG_LOAD_ERROR"
	ErrorCodeConfigNotFound = "CONFIG_NOT_FOUND"
	ErrorCodeConfigCreate   = "CONFIG_CREATE_ERROR"
	ErrorCodeConfigSave     = "CONFIG_SAVE_ERROR"
	ErrorCodeConfigDelete   = "CONFIG_DELETE_ERROR"
	ErrorCodeConfigValidate = "CONFIG_VALIDATE_ERROR"

	// Input validation errors
	ErrorCodeInputValidation = "INPUT_VALIDATION_ERROR"
	ErrorCodeQueryLoad       = "QUERY_LOAD_ERROR"
	ErrorCodeVariablesLoad   = "VARIABLES_LOAD_ERROR"
	ErrorCodeFilesParse      = "FILES_PARSE_ERROR"
	ErrorCodeFilesListParse  = "FILES_LIST_PARSE_ERROR"

	// GraphQL execution errors
	ErrorCodeGraphQLExecution = "GRAPHQL_EXECUTION_ERROR"
	ErrorCodeGraphQLErrors    = "GRAPHQL_ERRORS"
	ErrorCodeNetworkError     = "NETWORK_ERROR"
	ErrorCodeAuthError        = "AUTH_ERROR"

	// Schema errors
	ErrorCodeSchemaLoad       = "SCHEMA_LOAD_ERROR"
	ErrorCodeSchemaIntrospect = "SCHEMA_INTROSPECT_ERROR"
	ErrorCodeSchemaSave       = "SCHEMA_SAVE_ERROR"

	// System errors
	ErrorCodeSystemError      = "SYSTEM_ERROR"
	ErrorCodeFileNotFound     = "FILE_NOT_FOUND"
	ErrorCodePermissionDenied = "PERMISSION_DENIED"
)

Common error codes for AI agents

View Source
const (
	SSEMessageTypeNext     = "next"
	SSEMessageTypeError    = "error"
	SSEMessageTypeComplete = "complete"
)

SSE message types for graphql-sse protocol

View Source
const (
	MessageTypeConnectionInit = "connection_init"
	MessageTypeConnectionAck  = "connection_ack"
	MessageTypePing           = "ping"
	MessageTypePong           = "pong"
	MessageTypeSubscribe      = "subscribe"
	MessageTypeNext           = "next"
	MessageTypeError          = "error"
	MessageTypeComplete       = "complete"
)

GraphQL WebSocket Protocol Messages (graphql-transport-ws)

Variables

This section is empty.

Functions

func GetAvailableFormatters

func GetAvailableFormatters() []string

GetAvailableFormatters returns all available formatter names

func GetConfigPath

func GetConfigPath() string

GetConfigPath returns the path to the main configuration file. This is typically config.json in the default configuration directory.

func GetConfigPathForDir

func GetConfigPathForDir(configDir string) string

GetConfigPathForDir returns the path to the configuration file in a specific directory.

func GetDefaultPath

func GetDefaultPath() string

Public path functions GetDefaultPath returns the default configuration directory path for the current OS. On Linux: ~/.config/gqlt On macOS: ~/Library/Application Support/gqlt On Windows: %APPDATA%/gqlt

func GetGraphQLSchemaPathForConfigInDir

func GetGraphQLSchemaPathForConfigInDir(configName, configDir string) string

GetGraphQLSchemaPathForConfigInDir returns the path to the GraphQL SDL schema file for a specific configuration in a specific directory.

func GetJSONSchemaPathForConfigInDir

func GetJSONSchemaPathForConfigInDir(configName, configDir string) string

GetJSONSchemaPathForConfigInDir returns the path to the JSON schema file for a specific configuration in a specific directory.

func GetSchemaPath

func GetSchemaPath() string

GetSchemaPath returns the path to the default schema file. This is typically schema.json in the default configuration directory.

func GetSchemaPathForConfig

func GetSchemaPathForConfig(configName string) string

GetSchemaPathForConfig returns the path to the schema file for a specific configuration. This is typically schemas/{configName}.json in the default configuration directory.

func GetSchemaPathForConfigInDir

func GetSchemaPathForConfigInDir(configName, configDir string) string

GetSchemaPathForConfigInDir returns the path to the schema file for a specific configuration in a specific directory.

func GetSchemasDir

func GetSchemasDir() string

GetSchemasDir returns the path to the schemas directory. This is typically schemas/ in the default configuration directory.

func RegisterFormatter

func RegisterFormatter(name string, factory FormatterFactory)

RegisterFormatter registers a custom formatter with the default registry

func SDLToIntrospection added in v0.6.0

func SDLToIntrospection(sdl string) (interface{}, error)

SDLToIntrospection converts SDL schema text to introspection JSON format

func SaveGraphQLSchema

func SaveGraphQLSchema(schema *Response, filePath string) error

SaveGraphQLSchema saves the schema as GraphQL SDL

func SaveSchema

func SaveSchema(result *Response, path string) error

SaveSchema saves schema to a single file

func SaveSchemaDual

func SaveSchemaDual(result *Response, configName, configDir string) error

SaveSchemaDual saves schema in both JSON and GraphQL formats

func SchemaExists

func SchemaExists(path string) bool

SchemaExists checks if a schema file exists

func Version

func Version() string

Version returns the current version of the gqlt library

Types

type Analyzer

type Analyzer struct {
	// contains filtered or unexported fields
}

Analyzer handles GraphQL schema analysis and provides utilities for exploring and understanding GraphQL schemas. It can extract type information, field details, and generate human-readable descriptions of schema elements.

func LoadAnalyzerFromFile

func LoadAnalyzerFromFile(filePath string) (*Analyzer, error)

LoadAnalyzerFromFile creates a new schema analyzer by loading a schema from a JSON file. The file should contain a GraphQL introspection response in JSON format.

Example:

analyzer, err := gqlt.LoadAnalyzerFromFile("schema.json")
if err != nil {
    log.Fatal(err)
}

func NewAnalyzer

func NewAnalyzer(schema *Response) (*Analyzer, error)

NewAnalyzer creates a new schema analyzer from a GraphQL introspection response. The schema parameter should be the result of a GraphQL introspection query.

Example:

analyzer, err := gqlt.NewAnalyzer(introspectionResponse)
if err != nil {
    log.Fatal(err)
}

func (*Analyzer) FindField

func (a *Analyzer) FindField(rootType, fieldName string) (*FieldDescription, error)

FindField finds a field in a root type

func (*Analyzer) FindType

func (a *Analyzer) FindType(typeName string) (*TypeDescription, error)

FindType finds a type by name

func (*Analyzer) GetFieldDescription

func (a *Analyzer) GetFieldDescription(rootType string, fieldObj map[string]interface{}) (*FieldDescription, error)

GetFieldDescription gets a field description

func (*Analyzer) GetSummary

func (a *Analyzer) GetSummary() (*Summary, error)

GetSummary returns a summary of the schema

func (*Analyzer) GetTypeDescription

func (a *Analyzer) GetTypeDescription(typeName string) (*TypeDescription, error)

GetTypeDescription gets a type description by name

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a GraphQL client that can execute queries, mutations, and subscriptions against a GraphQL endpoint. It handles authentication, headers, and HTTP communication.

func NewClient

func NewClient(endpoint string, headers map[string]string) *Client

NewClient creates a new GraphQL client for the specified endpoint. The headers parameter can be nil or contain additional HTTP headers to send with requests.

Example:

client := gqlt.NewClient("https://api.example.com/graphql", map[string]string{
    "Authorization": "Bearer token",
})

func (*Client) Execute

func (c *Client) Execute(query string, variables map[string]interface{}, operationName string) (*Response, error)

Execute executes a GraphQL query, mutation, or subscription against the configured endpoint. The query parameter contains the GraphQL operation string, variables contains any variables to be passed to the operation, and operationName specifies which operation to execute (useful when the query contains multiple operations).

Example:

response, err := client.Execute(
    `query GetUser($id: ID!) { user(id: $id) { name email } }`,
    map[string]interface{}{"id": "123"},
    "GetUser",
)

func (*Client) ExecuteWithFiles

func (c *Client) ExecuteWithFiles(query string, variables map[string]interface{}, operationName string, files map[string]string) (*Response, error)

ExecuteWithFiles executes a GraphQL operation with file uploads using multipart/form-data. This method is used for GraphQL operations that require file uploads, such as mutations with Upload scalar types. The files parameter maps field names to file paths.

Example:

response, err := client.ExecuteWithFiles(
    `mutation UploadFile($file: Upload!) { uploadFile(file: $file) { id } }`,
    map[string]interface{}{"file": nil}, // File will be provided via files parameter
    "UploadFile",
    map[string]string{"file": "/path/to/file.jpg"},
)

func (*Client) FetchSDL added in v0.6.0

func (c *Client) FetchSDL() (string, error)

FetchSDL attempts to fetch the GraphQL schema in SDL format from common endpoint paths

func (*Client) Introspect

func (c *Client) Introspect() (*Response, error)

Introspect performs GraphQL introspection to get the schema

func (*Client) SetAuth

func (c *Client) SetAuth(username, password string)

SetAuth sets basic authentication for the client using the provided username and password. This will add an Authorization header with Basic authentication to all requests.

Example:

client.SetAuth("username", "password")

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string)

SetHeaders sets additional HTTP headers for the client. These headers will be sent with all subsequent requests.

Example:

client.SetHeaders(map[string]string{
    "Authorization": "Bearer token",
    "X-Custom-Header": "value",
})

func (*Client) Subscribe added in v0.8.0

func (c *Client) Subscribe(ctx context.Context, query string, variables map[string]interface{}, operationName string) (<-chan *SubscriptionMessage, <-chan error, error)

Subscribe establishes a GraphQL subscription over WebSocket and returns channels for messages and errors. The subscription runs until the context is cancelled, an error occurs, or the server closes the connection.

Example:

client := gqlt.NewClient("wss://api.example.com/graphql", nil)
messages, errors, err := client.Subscribe(ctx,
    `subscription { userCreated { id name } }`,
    nil,
    "UserCreated",
)
if err != nil {
    log.Fatal(err)
}

for msg := range messages {
    fmt.Printf("Received: %+v\n", msg)
}

type Config

type Config struct {
	Current string                 `json:"current"` // active config name (defaults to "default")
	Configs map[string]ConfigEntry `json:"configs"` // named configurations
}

Config represents the main configuration structure that manages multiple named configurations. It allows switching between different GraphQL endpoints and their associated settings.

func GetDefaultConfig

func GetDefaultConfig() *Config

GetDefaultConfig returns a default configuration

func Load

func Load(configDir string) (*Config, error)

Load reads a configuration file from the specified config directory. If configDir is empty, it searches in standard locations (current directory, then default path). Returns a Config struct with the loaded configuration or an error if loading fails.

Example:

config, err := gqlt.Load("/path/to/config")
if err != nil {
    log.Fatal(err)
}

func (*Config) Create

func (c *Config) Create(name string) error

Create creates a new configuration entry

func (*Config) Delete

func (c *Config) Delete(name string) error

Delete removes a configuration entry

func (*Config) GetCurrent

func (c *Config) GetCurrent() *ConfigEntry

GetCurrent returns the current active configuration entry. If the current configuration doesn't exist, it falls back to the "default" configuration, or creates a default entry if no configurations exist.

Example:

current := config.GetCurrent()
fmt.Printf("Current endpoint: %s\n", current.Endpoint)

func (*Config) Save

func (c *Config) Save(configDir string) error

Save writes the configuration to the specified config directory. Creates the directory if it doesn't exist and writes the configuration as JSON.

Example:

err := config.Save("/path/to/config")
if err != nil {
    log.Fatal(err)
}

func (*Config) SetCurrent

func (c *Config) SetCurrent(name string) error

SetCurrent sets the current active configuration

func (*Config) SetValue

func (c *Config) SetValue(name, key, value string) error

SetValue sets a value in a configuration entry

func (*Config) Validate

func (c *Config) Validate() []string

Validate checks if the configuration is valid

type ConfigEntry

type ConfigEntry struct {
	Endpoint string            `json:"endpoint"` // GraphQL endpoint URL
	Headers  map[string]string `json:"headers"`  // HTTP headers to send with requests
	Auth     struct {
		Token    string `json:"token,omitempty"`    // Bearer token for authentication
		Username string `json:"username,omitempty"` // Username for basic authentication
		Password string `json:"password,omitempty"` // Password for basic authentication
		APIKey   string `json:"api_key,omitempty"`  // API key for authentication
	} `json:"auth"`
	Comment string `json:"_comment,omitempty"` // AI-friendly documentation
}

ConfigEntry represents a single configuration for a GraphQL endpoint. It contains the endpoint URL, headers, authentication credentials, default output format, and optional documentation.

func (*ConfigEntry) GetHeaders added in v0.2.0

func (e *ConfigEntry) GetHeaders() map[string]string

GetHeaders returns the HTTP headers for this configuration entry, including computed authentication headers based on stored credentials.

type DescribeTypeInput added in v0.4.0

type DescribeTypeInput struct {
	TypeName   string            `json:"typeName" jsonschema:"The GraphQL type name to describe"`
	Endpoint   string            `json:"endpoint,omitempty" jsonschema:"GraphQL endpoint URL (required if schemaFile not provided)"`
	SchemaFile string            `json:"schemaFile,omitempty" jsonschema:"Local schema file path (JSON or SDL format, alternative to endpoint)"`
	Headers    map[string]string `json:"headers,omitempty" jsonschema:"HTTP headers to include (only used with endpoint)"`
	NoCache    bool              `json:"noCache,omitempty" jsonschema:"Skip cache and force fresh schema introspection (only used with endpoint)"`
}

DescribeTypeInput defines the input schema for the describe_type tool

type DescribeTypeOutput added in v0.4.0

type DescribeTypeOutput struct {
	TypeInfo string `json:"type_info" jsonschema:"Information about the GraphQL type"`
}

DescribeTypeOutput defines the output schema for the describe_type tool

type EnumValue

type EnumValue struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

EnumValue represents an enum value

type ErrorInfo

type ErrorInfo struct {
	Code    string                 `json:"code"`
	Message string                 `json:"message"`
	Details string                 `json:"details,omitempty"`
	Type    string                 `json:"type,omitempty"`
	Context map[string]interface{} `json:"context,omitempty"`
}

ErrorInfo provides structured error information

type ExecuteQueryInput added in v0.4.0

type ExecuteQueryInput struct {
	Query         string                 `json:"query" jsonschema:"The GraphQL query string"`
	Variables     map[string]interface{} `json:"variables,omitempty" jsonschema:"Variables to pass to the query"`
	OperationName string                 `json:"operationName,omitempty" jsonschema:"The operation name to execute"`
	Endpoint      string                 `json:"endpoint" jsonschema:"GraphQL endpoint URL (ws:// or wss:// for subscriptions)"`
	Headers       map[string]string      `json:"headers,omitempty" jsonschema:"HTTP headers to include"`
	Files         map[string]string      `` /* 130-byte string literal not displayed */
	Timeout       string                 `` /* 126-byte string literal not displayed */
	MaxMessages   int                    `` /* 137-byte string literal not displayed */
}

ExecuteQueryInput defines the input schema for the execute_query tool

type ExecuteQueryOutput added in v0.4.0

type ExecuteQueryOutput struct {
	Data      interface{} `json:"data" jsonschema:"The GraphQL response data"`
	Errors    interface{} `json:"errors,omitempty" jsonschema:"Any GraphQL errors"`
	ElapsedMs int64       `json:"elapsed_ms" jsonschema:"Query execution time in milliseconds"`
}

ExecuteQueryOutput defines the output schema for the execute_query tool

type FieldDescription

type FieldDescription struct {
	RootType    string         `json:"rootType"`
	Name        string         `json:"name"`
	Description string         `json:"description,omitempty"`
	Type        string         `json:"type"`
	Arguments   []FieldSummary `json:"arguments,omitempty"`
}

FieldDescription represents a field description

type FieldSummary

type FieldSummary struct {
	Name         string         `json:"name"`
	Description  string         `json:"description,omitempty"`
	Type         string         `json:"type"`
	Signature    string         `json:"signature"`
	DefaultValue string         `json:"defaultValue,omitempty"`
	Arguments    []FieldSummary `json:"arguments,omitempty"`
}

FieldSummary represents a field summary

type Formatter

type Formatter interface {
	FormatStructured(data interface{}, quiet bool) error
	FormatStructuredError(err error, code string, quiet bool) error
	FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error
	FormatResponse(response *Response, mode string) error
	SetOutput(writer io.Writer)
	SetErrorOutput(writer io.Writer)
}

Formatter defines the interface for output formatting. Implementations can format data as JSON, table, YAML, or other formats.

func NewFormatter

func NewFormatter(format string) Formatter

NewFormatter creates a new formatter using the default registry Returns the default JSON formatter if the requested format is not found

type FormatterFactory

type FormatterFactory func() Formatter

FormatterFactory creates a new formatter instance. This function type is used to register formatters in the registry.

type FormatterRegistry

type FormatterRegistry struct {
	// contains filtered or unexported fields
}

FormatterRegistry manages available formatters and provides a way to register and retrieve formatters by name.

func NewFormatterRegistry

func NewFormatterRegistry() *FormatterRegistry

NewFormatterRegistry creates a new formatter registry with default formatters (JSON, Table, YAML) already registered.

Example:

registry := gqlt.NewFormatterRegistry()
formatter, err := registry.Get("json")

func (*FormatterRegistry) Get

func (r *FormatterRegistry) Get(format string) (Formatter, error)

Get creates a new formatter instance for the specified format

func (*FormatterRegistry) List

func (r *FormatterRegistry) List() []string

List returns all registered formatter names

func (*FormatterRegistry) Register

func (r *FormatterRegistry) Register(name string, factory FormatterFactory)

Register adds a new formatter to the registry

type Input

type Input struct{}

Input handles input operations for loading queries, variables, headers, and files. It provides utilities for parsing and loading various types of input data.

func NewInput

func NewInput() *Input

NewInput creates a new input handler instance.

Example:

input := gqlt.NewInput()
query, err := input.LoadQuery("", "query.graphql")

func (*Input) LoadHeaders

func (i *Input) LoadHeaders(headers []string) map[string]string

LoadHeaders parses header strings into a map. Each header string should be in the format "Key: Value".

Example:

headers := input.LoadHeaders([]string{
    "Authorization: Bearer token",
    "Content-Type: application/json",
})

func (*Input) LoadQuery

func (i *Input) LoadQuery(query, queryFile string) (string, error)

LoadQuery loads a GraphQL query from a string or file. If query is provided, it returns the query string directly. If queryFile is provided, it reads and returns the file contents. If both are provided, query takes precedence.

Example:

query, err := input.LoadQuery("", "query.graphql")
if err != nil {
    log.Fatal(err)
}

func (*Input) LoadVariables

func (i *Input) LoadVariables(vars, varsFile string) (map[string]interface{}, error)

LoadVariables loads GraphQL variables from a JSON string or file. If vars is provided, it parses the JSON string directly. If varsFile is provided, it reads and parses the file contents. If both are provided, vars takes precedence.

Example:

variables, err := input.LoadVariables(`{"id": "123"}`, "")
if err != nil {
    log.Fatal(err)
}

func (*Input) ParseFiles

func (i *Input) ParseFiles(files []string) (map[string]string, error)

ParseFiles parses file upload specifications

func (*Input) ParseFilesFromList

func (i *Input) ParseFilesFromList(filesListPath string) ([]string, error)

ParseFilesFromList parses file upload specifications from a file

type Introspect

type Introspect struct {
	// contains filtered or unexported fields
}

Introspect handles GraphQL schema introspection operations. It provides utilities for introspecting GraphQL schemas and saving them to files.

func NewIntrospect

func NewIntrospect(client *Client) *Introspect

NewIntrospect creates a new introspection handler for the specified client.

Example:

client := gqlt.NewClient("https://api.example.com/graphql", nil)
introspect := gqlt.NewIntrospect(client)

func (*Introspect) IntrospectSchema

func (i *Introspect) IntrospectSchema() (*Response, error)

IntrospectSchema performs GraphQL introspection to get the schema from the endpoint. Returns a Response containing the complete GraphQL schema information.

Example:

schema, err := introspect.IntrospectSchema()
if err != nil {
    log.Fatal(err)
}

func (*Introspect) SaveSchema

func (i *Introspect) SaveSchema(schema *Response, filePath string) error

SaveSchema saves a schema response to a JSON file. The file will contain the complete introspection response in formatted JSON.

Example:

err := introspect.SaveSchema(schema, "schema.json")
if err != nil {
    log.Fatal(err)
}

type JSONFormatter

type JSONFormatter struct {
	// contains filtered or unexported fields
}

JSONFormatter implements Formatter for JSON output

func (*JSONFormatter) FormatJSON

func (f *JSONFormatter) FormatJSON(data interface{}) error

FormatJSON formats data as JSON with indentation

func (*JSONFormatter) FormatResponse

func (f *JSONFormatter) FormatResponse(response *Response, mode string) error

FormatResponse formats a GraphQL response as compact JSON

func (*JSONFormatter) FormatStructured

func (f *JSONFormatter) FormatStructured(data interface{}, quiet bool) error

FormatStructured formats data as structured JSON output

func (*JSONFormatter) FormatStructuredError

func (f *JSONFormatter) FormatStructuredError(err error, code string, quiet bool) error

FormatStructuredError formats an error as structured output

func (*JSONFormatter) FormatStructuredErrorWithContext

func (f *JSONFormatter) FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error

FormatStructuredErrorWithContext formats an error with additional context

func (*JSONFormatter) SetErrorOutput

func (f *JSONFormatter) SetErrorOutput(writer io.Writer)

SetErrorOutput sets the error output writer for the formatter

func (*JSONFormatter) SetOutput

func (f *JSONFormatter) SetOutput(writer io.Writer)

SetOutput sets the output writer for the formatter

func (*JSONFormatter) WriteToFile

func (f *JSONFormatter) WriteToFile(data interface{}, filename string) error

WriteToFile writes data to a file

type ListTypesInput added in v0.4.0

type ListTypesInput struct {
	Endpoint   string            `json:"endpoint,omitempty" jsonschema:"GraphQL endpoint URL (required if schemaFile not provided)"`
	SchemaFile string            `json:"schemaFile,omitempty" jsonschema:"Local schema file path (JSON or SDL format, alternative to endpoint)"`
	Filter     string            `json:"filter,omitempty" jsonschema:"Optional regex pattern to filter type names (e.g., 'Input.*', '.*Type', 'User.*')"`
	Kind       string            `json:"kind,omitempty" jsonschema:"Optional type kind filter (OBJECT, ENUM, SCALAR, UNION, INPUT_OBJECT, INTERFACE)"`
	Headers    map[string]string `json:"headers,omitempty" jsonschema:"HTTP headers to include (only used with endpoint)"`
	NoCache    bool              `json:"noCache,omitempty" jsonschema:"Skip cache and force fresh schema introspection (only used with endpoint)"`
}

ListTypesInput defines the input schema for the list_types tool

type ListTypesOutput added in v0.4.0

type ListTypesOutput struct {
	TypeNames []string `json:"type_names" jsonschema:"List of matching type names"`
	Count     int      `json:"count" jsonschema:"Total number of matching types"`
}

ListTypesOutput defines the output schema for the list_types tool

type MetaInfo

type MetaInfo struct {
	Command   string                 `json:"command,omitempty"`
	Timestamp string                 `json:"timestamp,omitempty"`
	Duration  string                 `json:"duration,omitempty"`
	Config    string                 `json:"config,omitempty"`
	Endpoint  string                 `json:"endpoint,omitempty"`
	Operation string                 `json:"operation,omitempty"`
	Variables map[string]interface{} `json:"variables,omitempty"`
}

MetaInfo provides metadata about the operation

type OperationInfo added in v0.8.0

type OperationInfo struct {
	Type OperationType
	Name string
}

OperationInfo contains information about a GraphQL operation

func DetectOperationType added in v0.8.0

func DetectOperationType(query string, operationName string) (*OperationInfo, error)

DetectOperationType parses a GraphQL document and detects the operation type. If operationName is provided, it finds that specific operation. If operationName is empty and there's only one operation, it uses that one. Returns an error if the operation can't be determined or doesn't exist.

type OperationType added in v0.8.0

type OperationType string

OperationType represents the type of a GraphQL operation

const (
	OperationTypeQuery        OperationType = "query"
	OperationTypeMutation     OperationType = "mutation"
	OperationTypeSubscription OperationType = "subscription"
)

type Response

type Response struct {
	Data       interface{}            `json:"data"`
	Errors     []interface{}          `json:"errors,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

Response represents a GraphQL response containing data, errors, and extensions. The Data field contains the actual response data, Errors contains any GraphQL errors, and Extensions contains additional metadata from the server.

type SDKServer added in v0.4.0

type SDKServer struct {
	// contains filtered or unexported fields
}

SDKServer wraps the official MCP SDK server with gqlt functionality

func NewSDKServer added in v0.4.0

func NewSDKServer() (*SDKServer, error)

NewSDKServer creates a new MCP server using the official SDK

func (*SDKServer) Start added in v0.4.0

func (s *SDKServer) Start(ctx context.Context, address string) error

Start starts the MCP server using stdin/stdout

func (*SDKServer) Stop added in v0.4.0

func (s *SDKServer) Stop(ctx context.Context) error

Stop stops the MCP server

type SSEEvent added in v0.8.0

type SSEEvent struct {
	Type string
	Data string
	ID   string
}

SSEEvent represents a parsed SSE event

type SSEMessage added in v0.8.0

type SSEMessage struct {
	Type    string                 `json:"type"`
	ID      string                 `json:"id,omitempty"`
	Payload map[string]interface{} `json:"payload,omitempty"`
}

SSEMessage represents a message received from SSE subscription

type SSEReader added in v0.8.0

type SSEReader struct {
	// contains filtered or unexported fields
}

SSEReader reads Server-Sent Events from an io.Reader

func NewSSEReader added in v0.8.0

func NewSSEReader(reader io.Reader) *SSEReader

NewSSEReader creates a new SSE reader

func (*SSEReader) ReadEvent added in v0.8.0

func (r *SSEReader) ReadEvent() (*SSEEvent, error)

ReadEvent reads the next SSE event

type SSESubscriptionClient added in v0.8.0

type SSESubscriptionClient struct {
	// contains filtered or unexported fields
}

SSESubscriptionClient handles GraphQL subscriptions over Server-Sent Events

func NewSSESubscriptionClient added in v0.8.0

func NewSSESubscriptionClient(url string, headers map[string]string) *SSESubscriptionClient

NewSSESubscriptionClient creates a new SSE subscription client

func (*SSESubscriptionClient) Subscribe added in v0.8.0

func (c *SSESubscriptionClient) Subscribe(ctx context.Context, query string, variables map[string]interface{}, operationName string) (<-chan *SubscriptionMessage, <-chan error, error)

Subscribe starts a subscription and returns channels for messages and errors

type Schema

type Schema struct {
	Endpoint string `json:"endpoint"`
	Headers  string `json:"headers"`
}

Schema represents the configuration schema for AI understanding

func GetSchema

func GetSchema() *Schema

GetSchema returns the configuration schema for AI understanding

type StructuredOutput

type StructuredOutput struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Error   *ErrorInfo  `json:"error,omitempty"`
	Meta    *MetaInfo   `json:"meta,omitempty"`
}

StructuredOutput represents a structured response for AI agents

type SubscriptionClient added in v0.8.0

type SubscriptionClient struct {
	// contains filtered or unexported fields
}

SubscriptionClient handles GraphQL subscriptions over WebSocket

func NewSubscriptionClient added in v0.8.0

func NewSubscriptionClient(url string, headers map[string]string) *SubscriptionClient

NewSubscriptionClient creates a new WebSocket subscription client

func (*SubscriptionClient) Close added in v0.8.0

func (c *SubscriptionClient) Close() error

Close closes the WebSocket connection

func (*SubscriptionClient) Connect added in v0.8.0

func (c *SubscriptionClient) Connect(ctx context.Context) error

Connect establishes a WebSocket connection and performs the connection handshake

func (*SubscriptionClient) Subscribe added in v0.8.0

func (c *SubscriptionClient) Subscribe(ctx context.Context, query string, variables map[string]interface{}, operationName string) (<-chan *SubscriptionMessage, <-chan error, error)

Subscribe sends a subscription request and returns a channel of messages

func (*SubscriptionClient) Unsubscribe added in v0.8.0

func (c *SubscriptionClient) Unsubscribe(ctx context.Context, subscriptionID string) error

Unsubscribe sends a complete message to stop the subscription

type SubscriptionMessage added in v0.8.0

type SubscriptionMessage struct {
	Data   interface{}   `json:"data,omitempty"`
	Errors []interface{} `json:"errors,omitempty"`
}

SubscriptionMessage represents a message received from a subscription

type Summary

type Summary struct {
	TotalTypes       int    `json:"totalTypes"`
	QueryType        string `json:"queryType,omitempty"`
	MutationType     string `json:"mutationType,omitempty"`
	SubscriptionType string `json:"subscriptionType,omitempty"`
}

Summary represents a schema summary

type TableFormatter

type TableFormatter struct {
	// contains filtered or unexported fields
}

TableFormatter implements Formatter for table output

func (*TableFormatter) FormatResponse

func (f *TableFormatter) FormatResponse(response *Response, mode string) error

FormatResponse formats a GraphQL response

func (*TableFormatter) FormatStructured

func (f *TableFormatter) FormatStructured(data interface{}, quiet bool) error

FormatStructured formats data as structured table output

func (*TableFormatter) FormatStructuredError

func (f *TableFormatter) FormatStructuredError(err error, code string, quiet bool) error

FormatStructuredError formats an error as structured table output

func (*TableFormatter) FormatStructuredErrorWithContext

func (f *TableFormatter) FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error

FormatStructuredErrorWithContext formats an error with additional context

func (*TableFormatter) SetErrorOutput

func (f *TableFormatter) SetErrorOutput(writer io.Writer)

SetErrorOutput sets the error output writer for the formatter

func (*TableFormatter) SetOutput

func (f *TableFormatter) SetOutput(writer io.Writer)

SetOutput sets the output writer for the formatter

type TypeDescription

type TypeDescription struct {
	Name        string         `json:"name"`
	Kind        string         `json:"kind"`
	Description string         `json:"description,omitempty"`
	Fields      []FieldSummary `json:"fields,omitempty"`
	InputFields []FieldSummary `json:"inputFields,omitempty"`
	EnumValues  []EnumValue    `json:"enumValues,omitempty"`
}

TypeDescription represents a type description

type VersionInput added in v0.5.3

type VersionInput struct {
}

VersionInput defines the input schema for the version tool

type VersionOutput added in v0.5.3

type VersionOutput struct {
	Version string `json:"version" jsonschema:"The current version of gqlt"`
}

VersionOutput defines the output schema for the version tool

type YAMLFormatter

type YAMLFormatter struct {
	// contains filtered or unexported fields
}

YAMLFormatter implements Formatter for YAML output

func (*YAMLFormatter) FormatResponse

func (f *YAMLFormatter) FormatResponse(response *Response, mode string) error

FormatResponse formats a GraphQL response

func (*YAMLFormatter) FormatStructured

func (f *YAMLFormatter) FormatStructured(data interface{}, quiet bool) error

FormatStructured formats data as structured YAML output

func (*YAMLFormatter) FormatStructuredError

func (f *YAMLFormatter) FormatStructuredError(err error, code string, quiet bool) error

FormatStructuredError formats an error as structured YAML output

func (*YAMLFormatter) FormatStructuredErrorWithContext

func (f *YAMLFormatter) FormatStructuredErrorWithContext(err error, code string, errorType string, context map[string]interface{}, quiet bool) error

FormatStructuredErrorWithContext formats an error with additional context

func (*YAMLFormatter) SetErrorOutput

func (f *YAMLFormatter) SetErrorOutput(writer io.Writer)

SetErrorOutput sets the error output writer for the formatter

func (*YAMLFormatter) SetOutput

func (f *YAMLFormatter) SetOutput(writer io.Writer)

SetOutput sets the output writer for the formatter

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL