npm package: @hurling/gql-schema-scout
Description: > **Beta Notice:** This package is in beta (pre-1.0.0). The API and interface may change between minor/patch versions without notice. A stable interface will be guaranteed from version 1.0.0 onwards.
Latest version: 0.0.10

# @hurling/gql-schema-scout

> **Beta Notice:** This package is in beta (pre-1.0.0). The API and interface may change between minor/patch versions without notice. A stable interface will be guaranteed from version 1.0.0 onwards.

A lightweight GraphQL schema exploration library designed for LLM/AI applications. It enables intelligent, context-aware retrieval of schema types based on natural language queries.

## Features

- **Semantic Schema Retrieval** - Pass a natural language query and get relevant GraphQL types
- **Multiple Input Sources** - Parse from SDL (Schema Definition Language) or introspection JSON
- **Optimized for LLMs** - Output formatted specifically for AI consumption
- **Serializable Lookups** - Pre-compute and cache schema lookups for fast initialization
- **TypeScript Support** - Full type definitions included

## Installation

```bash
npm install @hurling/gql-schema-scout
```

## CLI

```bash
npx @hurling/gql-schema-scout [options] [query]
```

### Options

- `-m, --minScore <number>` - Minimum relevance score (default: 0)
- `-r, --maxResults <number>` - Maximum number of types to return
- `-s, --schema <path>` - Path to GraphQL schema file or URL (required)
- `--splitCamelCase` - Split camelCase words into tokens
- `--expandRefs` - Expand type references (default: false)
- `--skipRootTypes` - Skip root types (Query, Mutation, Subscription) (default: false)
- `--noComments` - Don't search within field/type descriptions
- `--output <type>` - Output format: `sdl` or `minified` (default: `sdl`)

### Example

```bash
npx @hurling/gql-schema-scout --schema https://docs.github.com/public/fpt/schema.docs.graphql "issue"
```

Output:

```markdown
# the summarised relivant parts of the schema including types, enums, etc

# Summary of schema relevant to your query (18.4% of original, 81.6% reduction) - generated by @hurling/gql-schema-scout

# ⚠ 446 referenced types not fully defined.

# To see their full definition, call retrieveRelevantSchema() with expandRefs: true

"""Autogenerated input type of AddAssigneesToAssignable"""
type AddAssigneesToAssignableInput { ... }
...

# ... many more types ...

# ==================================================

SUMMARY: 18.4% of original (81.6% reduction)
Original: 1,428,564 chars
Output: 262,927 chars
```

The GitHub API schema (1.4M chars) was reduced to just ~263K chars for the "issue" query - making it practical for LLM context windows.

## Quick Start

```typescript
import { GQLSchemaScout } from "@hurling/gql-schema-scout";

const sdl = `
  type Query {
    user(id: ID!): User
    users(limit: Int): [User!]!
    posts(authorId: ID): [Post!]!
  }

  type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
  }

  type Post {
    id: ID!
    title: String!
    author: User!
  }
`;

const scout = GQLSchemaScout.fromSDL(sdl);

// Get relevant context for a user query
const context = scout.retrieveContext("user");
console.log(context);
```

Output:

```markdown
## Type: Query (Object)

Fields:

- user(id: ID!): User
- users(limit: Int): [User!]!
- posts(authorId: ID): [Post!]!

## Type: User (Object)

Fields:

- id: ID!
- name: String!
- email: String!
- posts: [Post!]!
  References: Post, Query
```

## Core Concepts

### Type Index

The type index maps type names to structured `TypeNode` objects containing:

- `name` - The type's name
- `kind` - Object, Input, Enum, Interface, or Union
- `fields` - Array of fields with args and return types
- `interfaces` - Interfaces implemented (for Object types)
- `referencedTypes` - Types referenced by fields

### Symbol Index

A reverse index mapping tokens (words from type/field names) to type names. Enables fuzzy matching:

- `user` → `User`, `Query`
- `users` → `User`, `Query` (singularized)
- `post` → `Post`, `Query`

### Context Retrieval

The library tokenizes your input, searches the symbol index for matching types, and expands to include referenced types. This gives you exactly what you need - no more, no less.

## Usage Patterns

### Basic: From SDL

```typescript
import { GQLSchemaScout } from "@hurling/gql-schema-scout";

const scout = GQLSchemaScout.fromSDL(yourSchemaSDL);
const context = scout.retrieveContext("create new post");
```

### Advanced: Pre-built Lookups

For better performance, pre-compute lookups at build time:

```typescript
import { buildLookupsFromSDL, saveLookups } from "@hurling/gql-schema-scout";

// Build once, save to file
const lookups = buildLookupsFromSDL(schemaSDL);
saveLookups({ lookups, filePath: "./schema-lookups.json" });
```

Then load at runtime:

```typescript
import { loadLookups, GQLSchemaScout } from "@hurling/gql-schema-scout";

const lookups = loadLookups({ filePath: "./schema-lookups.json" });
const scout = GQLSchemaScout.fromLookups(lookups);
const context = scout.retrieveContext("fetch posts");
```

### From Introspection JSON

```typescript
import { GQLSchemaScout } from "@hurling/gql-schema-scout";

// Fetch introspection from your endpoint
const response = await fetch("https://your-api.com/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query: "{ __schema { ... } }" }),
});
const introspection = await response.json();

const scout = GQLSchemaScout.fromIntrospection(introspection);
```

## API Reference

### `GQLSchemaScout`

Main class for schema exploration with fluent static factory methods.

```typescript
// From SDL string
const scout = GQLSchemaScout.fromSDL(sdl);

// From introspection result
const scout = GQLSchemaScout.fromIntrospection(introspection);

// From pre-built lookups
const scout = GQLSchemaScout.fromLookups(lookups);
```

**Instance Methods:**

- `retrieveContext(userInput: string): string` - Get relevant schema types
- `getTypeIndex(): TypeIndex` - Access raw type index
- `getSymbolIndex(): SymbolIndex` - Access symbol index
- `getSDL(): string` - Get original SDL (only available if created with fromSDL)
- `getLookups(): SchemaLookups` - Get serializable lookups

### Build Functions

- `buildLookupsFromSDL(sdl: string): SchemaLookups` - Build from SDL
- `buildLookupsFromIntrospection(introspection: IntrospectionQuery): SchemaLookups` - Build from introspection

### Serialization Functions

- `serializeLookups(lookups: SchemaLookups): string` - Convert to JSON string
- `deserializeLookups(data: string): SchemaLookups` - Parse from JSON string
- `saveLookups(options: SaveLookupsOptions): void` - Save to file
- `loadLookups(options: LoadLookupsOptions): SchemaLookups` - Load from file

### Utility Functions

- `tokenize(name: string): string[]` - Split name into searchable tokens
- `singularize(word: string): string` - Convert plural to singular

## Use Cases

### LLM Function Calling

Generate relevant schema context for function definitions:

```typescript
function getSchemaContext(userPrompt: string): string {
  return scout.retrieveContext(userPrompt);
}

// Prompt: "How do I create a new blog post?"
const context = getSchemaContext("create blog post");
// Returns: CreatePost mutation, Post type, CreatePostInput type
```

### IDE Autocomplete

Power intelligent autocomplete:

```typescript
function getSuggestions(partial: string): string[] {
  const context = explorer.retrieveContext(partial);
  // Parse and offer field suggestions
}
```

### API Documentation

Generate contextual docs:

```typescript
function generateDocs(query: string): string {
  return explorer.retrieveContext(query);
}
```

## License

MIT

---