Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ The `AgentToolkitConfig` object accepts:

### Operations

- `buildOperation(schema, fieldName, options?)` -- Generate a GraphQL operation string with variables
- `buildOperation(schema, fieldName, options?)` -- Generate a GraphQL operation string with variables. Set `options.operationType` to `query` or `mutation` to select the root explicitly when both use the same field name.

### MCP

Expand Down
8 changes: 4 additions & 4 deletions src/adapters/crewai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const namedTypeToJsonSchema = (
const required: string[] = [];
for (const field of namedType.inputFields) {
properties[field.name] = convertType(field.type, schema);
if (field.type.kind === 'NON_NULL') {
if (field.type.kind === 'NON_NULL' && field.defaultValue === null) {
required.push(field.name);
}
}
Expand Down Expand Up @@ -118,7 +118,7 @@ const buildArgumentsSchema = (

for (const argument of field.args) {
properties[argument.name] = typeReferenceToJsonSchema(argument.type, schema);
if (argument.type.kind === 'NON_NULL') {
if (argument.type.kind === 'NON_NULL' && argument.defaultValue === null) {
required.push(argument.name);
}
}
Expand Down Expand Up @@ -156,7 +156,7 @@ export const createCrewAITools = (
args_schema: argumentsSchema,
description,
func: async (parameters: Record<string, unknown>): Promise<string> => {
const op = buildOperation(schema, field.name, { maxDepth });
const op = buildOperation(schema, field.name, { maxDepth, operationType: 'query' });
return executor.execute(op.operation, parameters);
},
name: toolName,
Expand All @@ -176,7 +176,7 @@ export const createCrewAITools = (
args_schema: argumentsSchema,
description,
func: async (parameters: Record<string, unknown>): Promise<string> => {
const op = buildOperation(schema, field.name, { maxDepth });
const op = buildOperation(schema, field.name, { maxDepth, operationType: 'mutation' });
return executor.execute(op.operation, parameters);
},
name: toolName,
Expand Down
12 changes: 6 additions & 6 deletions src/adapters/langchain.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { z } from 'zod';
import { buildOperation } from '../operations/index.js';
import { typeReferenceToZod } from '../zod.js';
import { argumentToZod } from '../zod.js';
import { unwrapType } from '../operations/variables.js';
import type {
ParsedSchema,
Expand Down Expand Up @@ -50,7 +50,7 @@ const namedTypeToJsonSchema = (
const required: string[] = [];
for (const field of namedType.inputFields) {
properties[field.name] = convertType(field.type, schema);
if (field.type.kind === 'NON_NULL') {
if (field.type.kind === 'NON_NULL' && field.defaultValue === null) {
required.push(field.name);
}
}
Expand Down Expand Up @@ -124,7 +124,7 @@ const buildJsonSchema = (field: SchemaField, schema: ParsedSchema): Record<strin

for (const argument of field.args) {
properties[argument.name] = typeReferenceToJsonSchema(argument.type, schema);
if (argument.type.kind === 'NON_NULL') {
if (argument.type.kind === 'NON_NULL' && argument.defaultValue === null) {
required.push(argument.name);
}
}
Expand All @@ -149,7 +149,7 @@ const buildZodSchema = (
const shape: Record<string, z.ZodType> = {};

for (const argument of field.args) {
shape[argument.name] = typeReferenceToZod(argument.type, schema);
shape[argument.name] = argumentToZod(argument, schema);
}

return z.object(shape);
Expand Down Expand Up @@ -204,7 +204,7 @@ export const createLangChainTools = (
description,
func: async (input: string): Promise<string> => {
const variables = input ? JSON.parse(input) : {};
const op = buildOperation(schema, field.name, { maxDepth });
const op = buildOperation(schema, field.name, { maxDepth, operationType });
return executor.execute(op.operation, variables);
},
name: toolName,
Expand Down Expand Up @@ -234,7 +234,7 @@ export const createStructuredTools = (
return {
description,
func: async (input: Record<string, unknown>): Promise<string> => {
const op = buildOperation(schema, field.name, { maxDepth });
const op = buildOperation(schema, field.name, { maxDepth, operationType });
return executor.execute(op.operation, input);
},
name: toolName,
Expand Down
8 changes: 4 additions & 4 deletions src/adapters/vercel-ai.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { z } from 'zod';
import { buildOperation } from '../operations/index.js';
import { typeReferenceToZod } from '../zod.js';
import { argumentToZod } from '../zod.js';
import type { ParsedSchema, SchemaField } from '../types/index.js';
import type { GraphQLExecutor } from '../mcp/executor.js';

Expand All @@ -24,7 +24,7 @@ const buildParametersSchema = (
const shape: Record<string, z.ZodType> = {};

for (const argument of field.args) {
shape[argument.name] = typeReferenceToZod(argument.type, schema);
shape[argument.name] = argumentToZod(argument, schema);
}

return z.object(shape);
Expand Down Expand Up @@ -52,7 +52,7 @@ export const createVercelAITools = (
tools[toolName] = {
description,
execute: async (input: Record<string, unknown>): Promise<string> => {
const op = buildOperation(schema, field.name, { maxDepth });
const op = buildOperation(schema, field.name, { maxDepth, operationType: 'query' });
return executor.execute(op.operation, input);
},
parameters,
Expand All @@ -71,7 +71,7 @@ export const createVercelAITools = (
tools[toolName] = {
description,
execute: async (input: Record<string, unknown>): Promise<string> => {
const op = buildOperation(schema, field.name, { maxDepth });
const op = buildOperation(schema, field.name, { maxDepth, operationType: 'mutation' });
return executor.execute(op.operation, input);
},
parameters,
Expand Down
16 changes: 12 additions & 4 deletions src/mcp/tool-factory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { buildOperation } from '../operations/index.js';
import { typeReferenceToZod } from '../zod.js';
import { argumentToZod } from '../zod.js';
import type { z } from 'zod';
import type { ParsedSchema, SchemaField } from '../types/index.js';
import type { GraphQLExecutor } from './executor.js';
Expand All @@ -23,7 +23,7 @@ const buildInputSchema = (field: SchemaField, schema: ParsedSchema): Record<stri
const shape: Record<string, z.ZodType> = {};

for (const argument of field.args) {
shape[argument.name] = typeReferenceToZod(argument.type, schema);
shape[argument.name] = argumentToZod(argument, schema);
}

return shape;
Expand Down Expand Up @@ -56,7 +56,11 @@ export const createToolsFromSchema = (
tools.push({
description,
execute: async (parameters: Record<string, unknown>) => {
const op = buildOperation(schema, field.name, { includeDeprecated, maxDepth });
const op = buildOperation(schema, field.name, {
includeDeprecated,
maxDepth,
operationType: 'query',
});
return executor.execute(op.operation, parameters);
},
inputSchema,
Expand All @@ -81,7 +85,11 @@ export const createToolsFromSchema = (
tools.push({
description,
execute: async (parameters: Record<string, unknown>) => {
const op = buildOperation(schema, field.name, { includeDeprecated, maxDepth });
const op = buildOperation(schema, field.name, {
includeDeprecated,
maxDepth,
operationType: 'mutation',
});
return executor.execute(op.operation, parameters);
},
inputSchema,
Expand Down
71 changes: 45 additions & 26 deletions src/operations/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export interface GeneratedOperation {

export interface BuildOperationOptions {
maxDepth?: number;
operationType?: 'query' | 'mutation';
includeDeprecated?: boolean;
}

Expand Down Expand Up @@ -65,6 +66,11 @@ const buildSelectionSet = (typeName: string, context: SelectionContext): string
// Only include scalar fields to break the cycle
const scalarFields = type.fields
.filter((field) => !field.isDeprecated || isDeprecatedIncluded)
.filter((field) =>
field.args.every(
(argument) => !isRequired(argument.type) || argument.defaultValue !== null,
),
)
.filter((f) => isScalarLike(schema, f));

if (scalarFields.length === 0) {
Expand All @@ -77,7 +83,11 @@ const buildSelectionSet = (typeName: string, context: SelectionContext): string

visited.add(typeName);

const fields = type.fields.filter((field) => !field.isDeprecated || isDeprecatedIncluded);
const fields = type.fields
.filter((field) => !field.isDeprecated || isDeprecatedIncluded)
.filter((field) =>
field.args.every((argument) => !isRequired(argument.type) || argument.defaultValue !== null),
);
const lines: string[] = [];

for (const field of fields) {
Expand Down Expand Up @@ -109,6 +119,26 @@ const buildSelectionSet = (typeName: string, context: SelectionContext): string

const capitalize = (input: string): string => input.charAt(0).toUpperCase() + input.slice(1);

const resolveRootField = (
schema: ParsedSchema,
name: string,
preferredType?: 'query' | 'mutation',
): { rootField: SchemaField; operationType: 'query' | 'mutation' } => {
const operationTypes: ('query' | 'mutation')[] = preferredType
? [preferredType]
: ['query', 'mutation'];
for (const operationType of operationTypes) {
const rootName = operationType === 'query' ? schema.queryType : schema.mutationType;
const rootField = rootName
? schema.types.get(rootName)?.fields.find((field) => field.name === name)
: undefined;
if (rootField) {
return { operationType, rootField };
}
}
throw new Error(`Field "${name}" not found in schema query or mutation types`);
};

export const buildOperation = (
schema: ParsedSchema,
rootFieldName: string,
Expand All @@ -117,42 +147,29 @@ export const buildOperation = (
const maxDepth = options?.maxDepth ?? 2;
const isDeprecatedIncluded = options?.includeDeprecated ?? false;

// Look up the field in query type first, then mutation type
let operationType: 'query' | 'mutation' = 'query';
let rootField: SchemaField | undefined;

const queryType = schema.types.get(schema.queryType);
if (queryType) {
rootField = queryType.fields.find((f) => f.name === rootFieldName);
}

if (!rootField && schema.mutationType) {
const mutationType = schema.types.get(schema.mutationType);
if (mutationType) {
rootField = mutationType.fields.find((f) => f.name === rootFieldName);
if (rootField) {
operationType = 'mutation';
}
}
}

if (!rootField) {
throw new Error(`Field "${rootFieldName}" not found in schema query or mutation types`);
}
const { rootField, operationType } = resolveRootField(
schema,
rootFieldName,
options?.operationType,
);

const operationName = `${capitalize(rootFieldName)}${capitalize(operationType)}`;

// Build variable definitions from arguments
const variables: VariableDefinition[] = rootField.args.map((argument) => ({
description: argument.description,
name: argument.name,
required: isRequired(argument.type),
required: isRequired(argument.type) && argument.defaultValue === null,
type: typeReferenceToString(argument.type),
}));

// Build the variable definitions string for the operation
const variableDefinitions = variables
.map((variable) => `$${variable.name}: ${variable.type}`)
.map((variable, index) => {
const defaultValue = rootField.args[index]?.defaultValue;
const suffix = typeof defaultValue === 'string' ? ` = ${defaultValue}` : '';
return `$${variable.name}: ${variable.type}${suffix}`;
})
.join(', ');
const variableDefs = variables.length > 0 ? `(${variableDefinitions})` : '';

Expand All @@ -175,7 +192,9 @@ export const buildOperation = (
visited: new Set(),
})
: '';
const selectionSet = nestedSelection ? ` ${nestedSelection}` : '';
const selectionSet = isScalarLike(schema, rootField)
? ''
: ` ${nestedSelection || '{ __typename }'}`;

const operation = `${operationType} ${operationName}${variableDefs} {\n ${rootFieldName}${argumentsPassing}${selectionSet}\n}`;

Expand Down
2 changes: 1 addition & 1 deletion src/summarizer/summarizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const summarizeResponse = (
config?: Partial<SummaryConfig>,
): { summary: unknown; metadata: SummaryMetadata } => {
const resolvedConfig = { ...DEFAULT_CONFIG, ...config };
const originalSize = JSON.stringify(data).length;
const originalSize = JSON.stringify(data)?.length ?? 0;
let isTruncated = false;

const countItems = (value: unknown): number => {
Expand Down
Loading
Loading