graphql-agent-toolkit 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1726 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ GraphQLExecutor: () => GraphQLExecutor,
24
+ SchemaNavigator: () => SchemaNavigator,
25
+ buildOperation: () => buildOperation,
26
+ createAgentToolkitServer: () => createAgentToolkitServer,
27
+ createCrewAITools: () => createCrewAITools,
28
+ createLangChainTools: () => createLangChainTools,
29
+ createMockExecutor: () => createMockExecutor,
30
+ createStructuredTools: () => createStructuredTools,
31
+ createToolsFromSchema: () => createToolsFromSchema,
32
+ createVercelAITools: () => createVercelAITools,
33
+ detectPaginationStyle: () => detectPaginationStyle,
34
+ executePaginated: () => executePaginated,
35
+ fetchSchema: () => fetchSchema,
36
+ formatForLLM: () => formatForLLM,
37
+ generateMockData: () => generateMockData,
38
+ parseSchema: () => parseSchema,
39
+ summarizeResponse: () => summarizeResponse
40
+ });
41
+ module.exports = __toCommonJS(index_exports);
42
+
43
+ // src/introspection/fetcher.ts
44
+ var import_graphql = require("graphql");
45
+ var import_graphql_request = require("graphql-request");
46
+ async function fetchSchema(options) {
47
+ const client = new import_graphql_request.GraphQLClient(options.endpoint, {
48
+ headers: options.headers
49
+ });
50
+ const query = (0, import_graphql.getIntrospectionQuery)();
51
+ try {
52
+ const result = await client.request(query);
53
+ return result;
54
+ } catch (error) {
55
+ if (error instanceof Error) {
56
+ throw new Error(`Failed to fetch schema from ${options.endpoint}: ${error.message}`);
57
+ }
58
+ throw new Error(`Failed to fetch schema from ${options.endpoint}: Unknown error`);
59
+ }
60
+ }
61
+
62
+ // src/introspection/parser.ts
63
+ function convertTypeRef(introspectionType) {
64
+ return {
65
+ kind: introspectionType.kind,
66
+ name: introspectionType.name ?? null,
67
+ ofType: introspectionType.ofType ? convertTypeRef(
68
+ introspectionType.ofType
69
+ ) : null
70
+ };
71
+ }
72
+ function convertArgument(arg) {
73
+ return {
74
+ name: arg.name,
75
+ description: arg.description ?? null,
76
+ type: convertTypeRef(arg.type),
77
+ defaultValue: arg.defaultValue ?? null
78
+ };
79
+ }
80
+ function convertField(field) {
81
+ return {
82
+ name: field.name,
83
+ description: field.description ?? null,
84
+ type: convertTypeRef(field.type),
85
+ args: (field.args ?? []).map(convertArgument),
86
+ isDeprecated: field.isDeprecated ?? false
87
+ };
88
+ }
89
+ function parseSchema(introspectionResult) {
90
+ const schema = introspectionResult.__schema;
91
+ const types = /* @__PURE__ */ new Map();
92
+ for (const type of schema.types) {
93
+ if (type.name.startsWith("__")) {
94
+ continue;
95
+ }
96
+ const schemaType = {
97
+ name: type.name,
98
+ kind: type.kind,
99
+ description: type.description ?? null,
100
+ fields: "fields" in type && type.fields ? type.fields.map(convertField) : [],
101
+ inputFields: "inputFields" in type && type.inputFields ? type.inputFields.map(convertArgument) : [],
102
+ enumValues: "enumValues" in type && type.enumValues ? type.enumValues.map((v) => ({
103
+ name: v.name,
104
+ description: v.description ?? null
105
+ })) : [],
106
+ interfaces: "interfaces" in type && type.interfaces ? type.interfaces.map((i) => i.name) : [],
107
+ possibleTypes: "possibleTypes" in type && type.possibleTypes ? type.possibleTypes.map((t) => t.name) : []
108
+ };
109
+ types.set(type.name, schemaType);
110
+ }
111
+ return {
112
+ queryType: schema.queryType.name,
113
+ mutationType: schema.mutationType?.name ?? null,
114
+ subscriptionType: schema.subscriptionType?.name ?? null,
115
+ types
116
+ };
117
+ }
118
+
119
+ // src/operations/variables.ts
120
+ function typeRefToString(typeRef) {
121
+ if (typeRef.kind === "NON_NULL") {
122
+ if (!typeRef.ofType) {
123
+ return "Unknown!";
124
+ }
125
+ return `${typeRefToString(typeRef.ofType)}!`;
126
+ }
127
+ if (typeRef.kind === "LIST") {
128
+ if (!typeRef.ofType) {
129
+ return "[Unknown]";
130
+ }
131
+ return `[${typeRefToString(typeRef.ofType)}]`;
132
+ }
133
+ return typeRef.name ?? "Unknown";
134
+ }
135
+ function isRequired(typeRef) {
136
+ return typeRef.kind === "NON_NULL";
137
+ }
138
+ function unwrapType(typeRef) {
139
+ if (typeRef.kind === "NON_NULL" || typeRef.kind === "LIST") {
140
+ if (typeRef.ofType) {
141
+ return unwrapType(typeRef.ofType);
142
+ }
143
+ }
144
+ return typeRef;
145
+ }
146
+
147
+ // src/operations/builder.ts
148
+ var SCALAR_KINDS = /* @__PURE__ */ new Set(["SCALAR", "ENUM"]);
149
+ function isScalarLike(schema, field) {
150
+ const unwrapped = unwrapType(field.type);
151
+ if (SCALAR_KINDS.has(unwrapped.kind)) {
152
+ return true;
153
+ }
154
+ if (unwrapped.name) {
155
+ const namedType = schema.types.get(unwrapped.name);
156
+ if (namedType && SCALAR_KINDS.has(namedType.kind)) {
157
+ return true;
158
+ }
159
+ }
160
+ return false;
161
+ }
162
+ function buildSelectionSet(schema, typeName, currentDepth, maxDepth, visited, includeDeprecated, indentLevel = 2) {
163
+ if (currentDepth >= maxDepth) {
164
+ return "";
165
+ }
166
+ const type = schema.types.get(typeName);
167
+ if (!type || type.fields.length === 0) {
168
+ return "";
169
+ }
170
+ const fieldIndent = " ".repeat(indentLevel + 1);
171
+ const closingIndent = " ".repeat(indentLevel);
172
+ if (visited.has(typeName)) {
173
+ const scalarFields = type.fields.filter((f) => !f.isDeprecated || includeDeprecated).filter((f) => isScalarLike(schema, f));
174
+ if (scalarFields.length === 0) {
175
+ return "";
176
+ }
177
+ return `{
178
+ ${scalarFields.map((f) => `${fieldIndent}${f.name}`).join("\n")}
179
+ ${closingIndent}}`;
180
+ }
181
+ visited.add(typeName);
182
+ const fields = type.fields.filter((f) => !f.isDeprecated || includeDeprecated);
183
+ const lines = [];
184
+ for (const field of fields) {
185
+ const unwrapped = unwrapType(field.type);
186
+ if (isScalarLike(schema, field)) {
187
+ lines.push(`${fieldIndent}${field.name}`);
188
+ } else if (unwrapped.name) {
189
+ const nestedSelection = buildSelectionSet(
190
+ schema,
191
+ unwrapped.name,
192
+ currentDepth + 1,
193
+ maxDepth,
194
+ new Set(visited),
195
+ includeDeprecated,
196
+ indentLevel + 1
197
+ );
198
+ if (nestedSelection) {
199
+ lines.push(`${fieldIndent}${field.name} ${nestedSelection}`);
200
+ }
201
+ }
202
+ }
203
+ visited.delete(typeName);
204
+ if (lines.length === 0) {
205
+ return "";
206
+ }
207
+ return `{
208
+ ${lines.join("\n")}
209
+ ${closingIndent}}`;
210
+ }
211
+ function capitalize(str) {
212
+ return str.charAt(0).toUpperCase() + str.slice(1);
213
+ }
214
+ function buildOperation(schema, rootFieldName, options) {
215
+ const maxDepth = options?.maxDepth ?? 2;
216
+ const includeDeprecated = options?.includeDeprecated ?? false;
217
+ let operationType = "query";
218
+ let rootField;
219
+ const queryType = schema.types.get(schema.queryType);
220
+ if (queryType) {
221
+ rootField = queryType.fields.find((f) => f.name === rootFieldName);
222
+ }
223
+ if (!rootField && schema.mutationType) {
224
+ const mutationType = schema.types.get(schema.mutationType);
225
+ if (mutationType) {
226
+ rootField = mutationType.fields.find((f) => f.name === rootFieldName);
227
+ if (rootField) {
228
+ operationType = "mutation";
229
+ }
230
+ }
231
+ }
232
+ if (!rootField) {
233
+ throw new Error(`Field "${rootFieldName}" not found in schema query or mutation types`);
234
+ }
235
+ const operationName = `${capitalize(rootFieldName)}${capitalize(operationType)}`;
236
+ const variables = rootField.args.map((arg) => ({
237
+ name: arg.name,
238
+ type: typeRefToString(arg.type),
239
+ required: isRequired(arg.type),
240
+ description: arg.description
241
+ }));
242
+ const varDefs = variables.length > 0 ? `(${variables.map((v) => `$${v.name}: ${v.type}`).join(", ")})` : "";
243
+ const argsPassing = rootField.args.length > 0 ? `(${rootField.args.map((a) => `${a.name}: $${a.name}`).join(", ")})` : "";
244
+ const unwrapped = unwrapType(rootField.type);
245
+ let selectionSet = "";
246
+ if (!isScalarLike(schema, rootField) && unwrapped.name) {
247
+ selectionSet = ` ${buildSelectionSet(
248
+ schema,
249
+ unwrapped.name,
250
+ 0,
251
+ maxDepth,
252
+ /* @__PURE__ */ new Set(),
253
+ includeDeprecated,
254
+ 1
255
+ )}`;
256
+ }
257
+ const operation = `${operationType} ${operationName}${varDefs} {
258
+ ${rootFieldName}${argsPassing}${selectionSet}
259
+ }`;
260
+ return {
261
+ operation,
262
+ operationName,
263
+ variables,
264
+ operationType
265
+ };
266
+ }
267
+
268
+ // src/mcp/server.ts
269
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
270
+ var import_zod2 = require("zod");
271
+
272
+ // src/mcp/executor.ts
273
+ var import_graphql_request2 = require("graphql-request");
274
+ var GraphQLExecutor = class {
275
+ client;
276
+ constructor(endpoint, headers) {
277
+ this.client = new import_graphql_request2.GraphQLClient(endpoint, { headers });
278
+ }
279
+ async execute(operation, variables, additionalHeaders) {
280
+ try {
281
+ const result = await this.client.request(operation, variables, additionalHeaders);
282
+ return JSON.stringify(result, null, 2);
283
+ } catch (error) {
284
+ if (error instanceof Error) {
285
+ throw new Error(`GraphQL execution failed: ${error.message}`);
286
+ }
287
+ throw new Error("GraphQL execution failed: Unknown error");
288
+ }
289
+ }
290
+ };
291
+
292
+ // src/mcp/tool-factory.ts
293
+ var import_zod = require("zod");
294
+ function typeRefToZod(typeRef, schema) {
295
+ if (typeRef.kind === "NON_NULL") {
296
+ if (!typeRef.ofType) return import_zod.z.unknown();
297
+ return typeRefToZod(typeRef.ofType, schema);
298
+ }
299
+ if (typeRef.kind === "LIST") {
300
+ if (!typeRef.ofType) return import_zod.z.array(import_zod.z.unknown());
301
+ return import_zod.z.array(typeRefToZod(typeRef.ofType, schema)).optional();
302
+ }
303
+ const unwrapped = unwrapType(typeRef);
304
+ const typeName = unwrapped.name;
305
+ if (typeName) {
306
+ const namedType = schema.types.get(typeName);
307
+ if (namedType && namedType.kind === "ENUM" && namedType.enumValues.length > 0) {
308
+ const values = namedType.enumValues.map((v) => v.name);
309
+ return import_zod.z.enum(values).optional();
310
+ }
311
+ if (namedType && namedType.kind === "INPUT_OBJECT") {
312
+ const shape = {};
313
+ for (const field of namedType.inputFields) {
314
+ const fieldSchema = typeRefToZod(field.type, schema);
315
+ if (field.type.kind === "NON_NULL") {
316
+ shape[field.name] = fieldSchema;
317
+ } else {
318
+ shape[field.name] = fieldSchema.optional();
319
+ }
320
+ }
321
+ return import_zod.z.object(shape);
322
+ }
323
+ }
324
+ switch (typeName) {
325
+ case "String":
326
+ return import_zod.z.string().optional();
327
+ case "Int":
328
+ return import_zod.z.number().int().optional();
329
+ case "Float":
330
+ return import_zod.z.number().optional();
331
+ case "Boolean":
332
+ return import_zod.z.boolean().optional();
333
+ case "ID":
334
+ return import_zod.z.string().optional();
335
+ default:
336
+ return import_zod.z.unknown().optional();
337
+ }
338
+ }
339
+ function buildInputSchema(field, schema) {
340
+ const shape = {};
341
+ for (const arg of field.args) {
342
+ const zodType = typeRefToZod(arg.type, schema);
343
+ if (arg.type.kind === "NON_NULL") {
344
+ shape[arg.name] = zodType;
345
+ } else {
346
+ shape[arg.name] = zodType.optional();
347
+ }
348
+ }
349
+ return shape;
350
+ }
351
+ function createToolsFromSchema(schema, executor, options) {
352
+ const maxDepth = options?.maxDepth ?? 2;
353
+ const includeDeprecated = options?.includeDeprecated ?? false;
354
+ const tools = [];
355
+ const queryType = schema.types.get(schema.queryType);
356
+ if (queryType) {
357
+ for (const field of queryType.fields) {
358
+ if (field.isDeprecated && !includeDeprecated) continue;
359
+ const toolName = `query_${field.name}`;
360
+ const description = field.description || `Query ${field.name}`;
361
+ const inputSchema = buildInputSchema(field, schema);
362
+ tools.push({
363
+ name: toolName,
364
+ description,
365
+ inputSchema,
366
+ execute: async (args) => {
367
+ const op = buildOperation(schema, field.name, { maxDepth, includeDeprecated });
368
+ return executor.execute(op.operation, args);
369
+ }
370
+ });
371
+ }
372
+ }
373
+ if (schema.mutationType) {
374
+ const mutationType = schema.types.get(schema.mutationType);
375
+ if (mutationType) {
376
+ for (const field of mutationType.fields) {
377
+ if (field.isDeprecated && !includeDeprecated) continue;
378
+ const toolName = `mutate_${field.name}`;
379
+ const description = field.description || `Mutation ${field.name}`;
380
+ const inputSchema = buildInputSchema(field, schema);
381
+ tools.push({
382
+ name: toolName,
383
+ description,
384
+ inputSchema,
385
+ execute: async (args) => {
386
+ const op = buildOperation(schema, field.name, { maxDepth, includeDeprecated });
387
+ return executor.execute(op.operation, args);
388
+ }
389
+ });
390
+ }
391
+ }
392
+ }
393
+ return tools;
394
+ }
395
+
396
+ // src/mcp/server.ts
397
+ var packageVersion = "1.0.0";
398
+ async function createAgentToolkitServer(config, options) {
399
+ const serverName = options?.serverName ?? "graphql-agent-toolkit";
400
+ const serverVersion = options?.serverVersion ?? packageVersion;
401
+ const introspectionResult = await fetchSchema({
402
+ endpoint: config.endpoint,
403
+ headers: config.headers
404
+ });
405
+ const schema = parseSchema(introspectionResult);
406
+ const executor = new GraphQLExecutor(config.endpoint, config.headers);
407
+ const tools = createToolsFromSchema(schema, executor, {
408
+ maxDepth: config.operationDepth ?? 2,
409
+ includeDeprecated: config.includeDeprecated ?? false
410
+ });
411
+ const server = new import_mcp.McpServer({
412
+ name: serverName,
413
+ version: serverVersion
414
+ });
415
+ for (const tool of tools) {
416
+ const inputSchema = Object.keys(tool.inputSchema).length > 0 ? tool.inputSchema : void 0;
417
+ if (inputSchema) {
418
+ server.tool(
419
+ tool.name,
420
+ tool.description,
421
+ inputSchema,
422
+ async (args) => {
423
+ try {
424
+ const result = await tool.execute(args);
425
+ return {
426
+ content: [{ type: "text", text: result }]
427
+ };
428
+ } catch (error) {
429
+ const message = error instanceof Error ? error.message : "Unknown error";
430
+ return {
431
+ content: [{ type: "text", text: `Error: ${message}` }],
432
+ isError: true
433
+ };
434
+ }
435
+ }
436
+ );
437
+ } else {
438
+ server.tool(
439
+ tool.name,
440
+ tool.description,
441
+ async () => {
442
+ try {
443
+ const result = await tool.execute({});
444
+ return {
445
+ content: [{ type: "text", text: result }]
446
+ };
447
+ } catch (error) {
448
+ const message = error instanceof Error ? error.message : "Unknown error";
449
+ return {
450
+ content: [{ type: "text", text: `Error: ${message}` }],
451
+ isError: true
452
+ };
453
+ }
454
+ }
455
+ );
456
+ }
457
+ }
458
+ server.tool(
459
+ "explore_schema",
460
+ "Explore the GraphQL schema \u2014 list types, fields, and arguments",
461
+ {
462
+ typeName: import_zod2.z.string().optional().describe("Type name to explore. If omitted, lists all types.")
463
+ },
464
+ async (args) => {
465
+ if (args.typeName) {
466
+ const type = schema.types.get(args.typeName);
467
+ if (!type) {
468
+ return {
469
+ content: [{ type: "text", text: `Type "${args.typeName}" not found.` }]
470
+ };
471
+ }
472
+ return {
473
+ content: [{ type: "text", text: JSON.stringify(type, null, 2) }]
474
+ };
475
+ }
476
+ const typeList = Array.from(schema.types.values()).filter((t) => !["SCALAR"].includes(t.kind)).map((t) => `${t.kind} ${t.name}${t.description ? ` \u2014 ${t.description}` : ""}`);
477
+ return {
478
+ content: [{ type: "text", text: typeList.join("\n") }]
479
+ };
480
+ }
481
+ );
482
+ return server;
483
+ }
484
+
485
+ // src/semantic/tokenizer.ts
486
+ var STOP_WORDS = /* @__PURE__ */ new Set([
487
+ "a",
488
+ "an",
489
+ "the",
490
+ "is",
491
+ "are",
492
+ "was",
493
+ "were",
494
+ "be",
495
+ "been",
496
+ "being",
497
+ "have",
498
+ "has",
499
+ "had",
500
+ "do",
501
+ "does",
502
+ "did",
503
+ "will",
504
+ "would",
505
+ "could",
506
+ "should",
507
+ "may",
508
+ "might",
509
+ "shall",
510
+ "can",
511
+ "need",
512
+ "dare",
513
+ "ought",
514
+ "used",
515
+ "to",
516
+ "of",
517
+ "in",
518
+ "for",
519
+ "on",
520
+ "with",
521
+ "at",
522
+ "by",
523
+ "from",
524
+ "as",
525
+ "into",
526
+ "through",
527
+ "during",
528
+ "before",
529
+ "after",
530
+ "above",
531
+ "below",
532
+ "between",
533
+ "out",
534
+ "off",
535
+ "over",
536
+ "under",
537
+ "again",
538
+ "further",
539
+ "then",
540
+ "once",
541
+ "and",
542
+ "but",
543
+ "or",
544
+ "nor",
545
+ "not",
546
+ "so",
547
+ "yet",
548
+ "both",
549
+ "either",
550
+ "neither",
551
+ "each",
552
+ "every",
553
+ "all",
554
+ "any",
555
+ "few",
556
+ "more",
557
+ "most",
558
+ "other",
559
+ "some",
560
+ "such",
561
+ "no",
562
+ "only",
563
+ "own",
564
+ "same",
565
+ "than",
566
+ "too",
567
+ "very",
568
+ "just",
569
+ "because",
570
+ "if",
571
+ "it",
572
+ "its",
573
+ "this",
574
+ "that",
575
+ "these",
576
+ "those",
577
+ "i",
578
+ "me",
579
+ "my",
580
+ "we",
581
+ "our",
582
+ "you",
583
+ "your",
584
+ "he",
585
+ "him",
586
+ "his",
587
+ "she",
588
+ "her",
589
+ "they",
590
+ "them",
591
+ "their",
592
+ "what",
593
+ "which",
594
+ "who",
595
+ "whom"
596
+ ]);
597
+ function tokenize(text) {
598
+ if (!text) return [];
599
+ const split = text.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[^a-zA-Z0-9]+/g, " ").toLowerCase().trim().split(/\s+/).filter((word) => word.length > 0);
600
+ return split.filter((word) => !STOP_WORDS.has(word));
601
+ }
602
+
603
+ // src/semantic/navigator.ts
604
+ var SchemaNavigator = class {
605
+ schema = null;
606
+ documents = [];
607
+ idf = /* @__PURE__ */ new Map();
608
+ /**
609
+ * Index a parsed schema for semantic search.
610
+ */
611
+ index(schema) {
612
+ this.schema = schema;
613
+ this.documents = [];
614
+ for (const [typeName, type] of schema.types) {
615
+ if (type.kind === "SCALAR") continue;
616
+ const textParts = [typeName];
617
+ if (type.description) {
618
+ textParts.push(type.description);
619
+ }
620
+ for (const field of type.fields) {
621
+ textParts.push(field.name);
622
+ if (field.description) {
623
+ textParts.push(field.description);
624
+ }
625
+ }
626
+ for (const field of type.inputFields) {
627
+ textParts.push(field.name);
628
+ if (field.description) {
629
+ textParts.push(field.description);
630
+ }
631
+ }
632
+ for (const ev of type.enumValues) {
633
+ textParts.push(ev.name);
634
+ if (ev.description) {
635
+ textParts.push(ev.description);
636
+ }
637
+ }
638
+ const tokens = tokenize(textParts.join(" "));
639
+ this.documents.push({ typeName, tokens, tfidf: /* @__PURE__ */ new Map() });
640
+ }
641
+ this.computeIdf();
642
+ for (const doc of this.documents) {
643
+ doc.tfidf = this.computeTfidf(doc.tokens);
644
+ }
645
+ }
646
+ /**
647
+ * Search the schema for types matching the query.
648
+ */
649
+ search(query, limit = 5) {
650
+ if (!this.schema || this.documents.length === 0) {
651
+ return [];
652
+ }
653
+ const queryTokens = tokenize(query);
654
+ if (queryTokens.length === 0) {
655
+ return [];
656
+ }
657
+ const queryTfidf = this.computeTfidf(queryTokens);
658
+ const scored = [];
659
+ for (const doc of this.documents) {
660
+ const score = this.cosineSimilarity(queryTfidf, doc.tfidf);
661
+ if (score > 0) {
662
+ const type = this.schema.types.get(doc.typeName);
663
+ scored.push({
664
+ typeName: doc.typeName,
665
+ score,
666
+ kind: type.kind,
667
+ description: type.description
668
+ });
669
+ }
670
+ }
671
+ scored.sort((a, b) => b.score - a.score);
672
+ return scored.slice(0, limit);
673
+ }
674
+ /**
675
+ * Get formatted context for a specific type.
676
+ */
677
+ getTypeContext(typeName) {
678
+ if (!this.schema) return null;
679
+ const type = this.schema.types.get(typeName);
680
+ if (!type) return null;
681
+ const lines = [];
682
+ lines.push(`${type.kind} ${type.name}`);
683
+ if (type.description) {
684
+ lines.push(` Description: ${type.description}`);
685
+ }
686
+ if (type.fields.length > 0) {
687
+ lines.push(" Fields:");
688
+ for (const field of type.fields) {
689
+ const desc = field.description ? ` \u2014 ${field.description}` : "";
690
+ const args = field.args.length > 0 ? `(${field.args.map((a) => a.name).join(", ")})` : "";
691
+ lines.push(` ${field.name}${args}${desc}`);
692
+ }
693
+ }
694
+ if (type.inputFields.length > 0) {
695
+ lines.push(" Input Fields:");
696
+ for (const field of type.inputFields) {
697
+ const desc = field.description ? ` \u2014 ${field.description}` : "";
698
+ lines.push(` ${field.name}${desc}`);
699
+ }
700
+ }
701
+ if (type.enumValues.length > 0) {
702
+ lines.push(" Enum Values:");
703
+ for (const ev of type.enumValues) {
704
+ const desc = ev.description ? ` \u2014 ${ev.description}` : "";
705
+ lines.push(` ${ev.name}${desc}`);
706
+ }
707
+ }
708
+ if (type.interfaces.length > 0) {
709
+ lines.push(` Implements: ${type.interfaces.join(", ")}`);
710
+ }
711
+ if (type.possibleTypes.length > 0) {
712
+ lines.push(` Possible Types: ${type.possibleTypes.join(", ")}`);
713
+ }
714
+ return lines.join("\n");
715
+ }
716
+ computeIdf() {
717
+ const docCount = this.documents.length;
718
+ const termDocFreq = /* @__PURE__ */ new Map();
719
+ for (const doc of this.documents) {
720
+ const uniqueTokens = new Set(doc.tokens);
721
+ for (const token of uniqueTokens) {
722
+ termDocFreq.set(token, (termDocFreq.get(token) ?? 0) + 1);
723
+ }
724
+ }
725
+ this.idf = /* @__PURE__ */ new Map();
726
+ for (const [term, freq] of termDocFreq) {
727
+ this.idf.set(term, Math.log(1 + docCount / (1 + freq)));
728
+ }
729
+ }
730
+ computeTfidf(tokens) {
731
+ const tf = /* @__PURE__ */ new Map();
732
+ for (const token of tokens) {
733
+ tf.set(token, (tf.get(token) ?? 0) + 1);
734
+ }
735
+ const tfidf = /* @__PURE__ */ new Map();
736
+ for (const [term, count] of tf) {
737
+ const idfVal = this.idf.get(term) ?? Math.log(1 + this.documents.length);
738
+ tfidf.set(term, count / tokens.length * idfVal);
739
+ }
740
+ return tfidf;
741
+ }
742
+ cosineSimilarity(a, b) {
743
+ let dotProduct = 0;
744
+ let normA = 0;
745
+ let normB = 0;
746
+ for (const [term, val] of a) {
747
+ normA += val * val;
748
+ const bVal = b.get(term);
749
+ if (bVal !== void 0) {
750
+ dotProduct += val * bVal;
751
+ }
752
+ }
753
+ for (const val of b.values()) {
754
+ normB += val * val;
755
+ }
756
+ if (normA === 0 || normB === 0) return 0;
757
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
758
+ }
759
+ };
760
+
761
+ // src/pagination/handler.ts
762
+ var DEFAULT_PAGE_SIZE = 20;
763
+ var DEFAULT_MAX_PAGES = 10;
764
+ function detectPaginationStyle(schema, typeName) {
765
+ const type = schema.types.get(typeName);
766
+ if (!type) return "none";
767
+ const edgesField = type.fields.find((f) => f.name === "edges");
768
+ const pageInfoField = type.fields.find((f) => f.name === "pageInfo");
769
+ if (edgesField && pageInfoField) {
770
+ const edgesTypeName = unwrapTypeName(edgesField.type);
771
+ if (edgesTypeName) {
772
+ const edgesType = schema.types.get(edgesTypeName);
773
+ if (edgesType) {
774
+ const hasNode = edgesType.fields.some((f) => f.name === "node");
775
+ if (hasNode) {
776
+ const pageInfoTypeName = unwrapTypeName(pageInfoField.type);
777
+ if (pageInfoTypeName) {
778
+ const pageInfoType = schema.types.get(pageInfoTypeName);
779
+ if (pageInfoType) {
780
+ const hasNextPage = pageInfoType.fields.some((f) => f.name === "hasNextPage");
781
+ const hasEndCursor = pageInfoType.fields.some((f) => f.name === "endCursor");
782
+ if (hasNextPage && hasEndCursor) {
783
+ return "relay";
784
+ }
785
+ }
786
+ }
787
+ }
788
+ }
789
+ }
790
+ }
791
+ const queryType = schema.types.get(schema.queryType);
792
+ if (queryType) {
793
+ for (const field of queryType.fields) {
794
+ const returnTypeName = unwrapTypeName(field.type);
795
+ if (returnTypeName === typeName) {
796
+ const argNames = field.args.map((a) => a.name);
797
+ const hasLimitOffset = argNames.includes("limit") && argNames.includes("offset");
798
+ const hasSkipTake = argNames.includes("skip") && argNames.includes("take");
799
+ if (hasLimitOffset || hasSkipTake) {
800
+ return "offset";
801
+ }
802
+ }
803
+ }
804
+ }
805
+ return "none";
806
+ }
807
+ async function executePaginated(executor, operation, variables, config) {
808
+ const style = config?.style ?? "auto";
809
+ const pageSize = config?.pageSize ?? DEFAULT_PAGE_SIZE;
810
+ const maxPages = config?.maxPages ?? DEFAULT_MAX_PAGES;
811
+ if (style === "relay" || style === "auto" && isRelayOperation(operation)) {
812
+ return executeRelayPaginated(executor, operation, variables, pageSize, maxPages);
813
+ }
814
+ if (style === "offset" || style === "auto" && isOffsetOperation(operation)) {
815
+ return executeOffsetPaginated(executor, operation, variables, pageSize, maxPages);
816
+ }
817
+ const resultStr = await executor.execute(operation, variables);
818
+ const data = JSON.parse(resultStr);
819
+ const items = extractItems(data);
820
+ return {
821
+ items,
822
+ totalFetched: items.length,
823
+ hasMore: false
824
+ };
825
+ }
826
+ function isRelayOperation(operation) {
827
+ return operation.includes("$after") && operation.includes("$first") && operation.includes("pageInfo");
828
+ }
829
+ function isOffsetOperation(operation) {
830
+ return operation.includes("$limit") && operation.includes("$offset") || operation.includes("$skip") && operation.includes("$take");
831
+ }
832
+ async function executeRelayPaginated(executor, operation, variables, pageSize, maxPages) {
833
+ const allItems = [];
834
+ let cursor = null;
835
+ let startCursor = null;
836
+ let hasMore = true;
837
+ let pageCount = 0;
838
+ while (hasMore && pageCount < maxPages) {
839
+ const vars = {
840
+ ...variables,
841
+ first: pageSize
842
+ };
843
+ if (cursor) {
844
+ vars.after = cursor;
845
+ }
846
+ const resultStr = await executor.execute(operation, vars);
847
+ const data = JSON.parse(resultStr);
848
+ const connectionData = findConnectionData(data);
849
+ if (!connectionData) {
850
+ break;
851
+ }
852
+ const { edges, pageInfo } = connectionData;
853
+ if (pageCount === 0 && pageInfo.startCursor) {
854
+ startCursor = pageInfo.startCursor;
855
+ }
856
+ for (const edge of edges) {
857
+ if (edge && typeof edge === "object" && "node" in edge) {
858
+ allItems.push(edge.node);
859
+ } else {
860
+ allItems.push(edge);
861
+ }
862
+ }
863
+ hasMore = pageInfo.hasNextPage ?? false;
864
+ cursor = pageInfo.endCursor ?? null;
865
+ pageCount++;
866
+ if (!hasMore || !cursor) break;
867
+ }
868
+ const result = {
869
+ items: allItems,
870
+ totalFetched: allItems.length,
871
+ hasMore
872
+ };
873
+ if (startCursor || cursor) {
874
+ result.cursors = {
875
+ start: startCursor ?? "",
876
+ end: cursor ?? ""
877
+ };
878
+ }
879
+ return result;
880
+ }
881
+ async function executeOffsetPaginated(executor, operation, variables, pageSize, maxPages) {
882
+ const allItems = [];
883
+ let currentOffset = 0;
884
+ let hasMore = true;
885
+ let pageCount = 0;
886
+ const useSkipTake = operation.includes("$skip") && operation.includes("$take");
887
+ while (hasMore && pageCount < maxPages) {
888
+ const vars = { ...variables };
889
+ if (useSkipTake) {
890
+ vars.skip = currentOffset;
891
+ vars.take = pageSize;
892
+ } else {
893
+ vars.offset = currentOffset;
894
+ vars.limit = pageSize;
895
+ }
896
+ const resultStr = await executor.execute(operation, vars);
897
+ const data = JSON.parse(resultStr);
898
+ const items = extractItems(data);
899
+ allItems.push(...items);
900
+ pageCount++;
901
+ if (items.length < pageSize) {
902
+ hasMore = false;
903
+ } else {
904
+ currentOffset += pageSize;
905
+ }
906
+ }
907
+ return {
908
+ items: allItems,
909
+ totalFetched: allItems.length,
910
+ hasMore
911
+ };
912
+ }
913
+ function findConnectionData(data) {
914
+ if (!data || typeof data !== "object") return null;
915
+ const obj = data;
916
+ if (Array.isArray(obj.edges) && obj.pageInfo && typeof obj.pageInfo === "object") {
917
+ return {
918
+ edges: obj.edges,
919
+ pageInfo: obj.pageInfo
920
+ };
921
+ }
922
+ for (const value of Object.values(obj)) {
923
+ if (value && typeof value === "object" && !Array.isArray(value)) {
924
+ const found = findConnectionData(value);
925
+ if (found) return found;
926
+ }
927
+ }
928
+ return null;
929
+ }
930
+ function extractItems(data) {
931
+ if (Array.isArray(data)) return data;
932
+ if (!data || typeof data !== "object") return [];
933
+ const obj = data;
934
+ for (const value of Object.values(obj)) {
935
+ if (Array.isArray(value)) return value;
936
+ if (value && typeof value === "object") {
937
+ const items = extractItems(value);
938
+ if (items.length > 0) return items;
939
+ }
940
+ }
941
+ return [];
942
+ }
943
+ function unwrapTypeName(typeRef) {
944
+ if (typeRef.kind === "NON_NULL" || typeRef.kind === "LIST") {
945
+ if (typeRef.ofType) {
946
+ return unwrapTypeName(typeRef.ofType);
947
+ }
948
+ return null;
949
+ }
950
+ return typeRef.name;
951
+ }
952
+
953
+ // src/summarizer/summarizer.ts
954
+ var DEFAULT_CONFIG = {
955
+ maxItems: 5,
956
+ maxDepth: 3,
957
+ maxStringLength: 200,
958
+ includeMetadata: true
959
+ };
960
+ function summarizeResponse(data, config) {
961
+ const cfg = { ...DEFAULT_CONFIG, ...config };
962
+ const originalSize = JSON.stringify(data).length;
963
+ let truncated = false;
964
+ let totalItems = 0;
965
+ function countItems(value) {
966
+ if (Array.isArray(value)) return value.length;
967
+ if (value && typeof value === "object") {
968
+ let count = 0;
969
+ for (const v of Object.values(value)) {
970
+ if (Array.isArray(v)) count += v.length;
971
+ else count += countItems(v);
972
+ }
973
+ return count;
974
+ }
975
+ return 0;
976
+ }
977
+ totalItems = countItems(data);
978
+ function summarize(value, depth) {
979
+ if (value === null || value === void 0) return value;
980
+ if (typeof value === "string") {
981
+ if (value.length > cfg.maxStringLength) {
982
+ truncated = true;
983
+ return value.slice(0, cfg.maxStringLength) + "...";
984
+ }
985
+ return value;
986
+ }
987
+ if (typeof value === "number" || typeof value === "boolean") {
988
+ return value;
989
+ }
990
+ if (Array.isArray(value)) {
991
+ if (depth >= cfg.maxDepth) {
992
+ truncated = true;
993
+ return `[...${value.length} items]`;
994
+ }
995
+ const items = value.slice(0, cfg.maxItems).map((item) => summarize(item, depth + 1));
996
+ if (value.length > cfg.maxItems) {
997
+ truncated = true;
998
+ if (cfg.includeMetadata) {
999
+ return Object.assign(items, {
1000
+ _meta: { totalCount: value.length, showing: cfg.maxItems }
1001
+ });
1002
+ }
1003
+ }
1004
+ return items;
1005
+ }
1006
+ if (typeof value === "object") {
1007
+ if (depth >= cfg.maxDepth) {
1008
+ const keys = Object.keys(value);
1009
+ truncated = true;
1010
+ return `{...${keys.length} keys}`;
1011
+ }
1012
+ const result = {};
1013
+ for (const [key, val] of Object.entries(value)) {
1014
+ result[key] = summarize(val, depth + 1);
1015
+ }
1016
+ return result;
1017
+ }
1018
+ return value;
1019
+ }
1020
+ const summary = summarize(data, 0);
1021
+ return {
1022
+ summary,
1023
+ metadata: {
1024
+ totalItems,
1025
+ truncated,
1026
+ originalSize
1027
+ }
1028
+ };
1029
+ }
1030
+ function formatForLLM(data, config) {
1031
+ const { summary } = summarizeResponse(data, config);
1032
+ return renderMarkdown(summary, 0);
1033
+ }
1034
+ function renderMarkdown(value, indent) {
1035
+ if (value === null || value === void 0) return "null";
1036
+ if (typeof value === "string") return value;
1037
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1038
+ if (Array.isArray(value)) {
1039
+ if (value.length === 0) return "(empty list)";
1040
+ const lines = [];
1041
+ const meta = value._meta;
1042
+ for (const item of value) {
1043
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
1044
+ const objLines = renderObjectAsBullets(item, indent + 1);
1045
+ lines.push(`${" ".repeat(indent)}- ${objLines}`);
1046
+ } else {
1047
+ lines.push(`${" ".repeat(indent)}- ${renderMarkdown(item, indent + 1)}`);
1048
+ }
1049
+ }
1050
+ if (meta) {
1051
+ lines.push(`${" ".repeat(indent)}- _(${meta.totalCount - meta.showing} more items...)_`);
1052
+ }
1053
+ return lines.join("\n");
1054
+ }
1055
+ if (typeof value === "object") {
1056
+ return renderObjectAsSection(value, indent);
1057
+ }
1058
+ return String(value);
1059
+ }
1060
+ function renderObjectAsBullets(obj, indent) {
1061
+ const entries = Object.entries(obj).filter(([k]) => k !== "_meta");
1062
+ if (entries.length === 0) return "(empty)";
1063
+ const parts = [];
1064
+ let first = true;
1065
+ for (const [key, value] of entries) {
1066
+ if (typeof value === "object" && value !== null) {
1067
+ if (first) {
1068
+ parts.push(`**${key}**: ${renderMarkdown(value, indent + 1)}`);
1069
+ first = false;
1070
+ } else {
1071
+ parts.push(`${" ".repeat(indent)}**${key}**: ${renderMarkdown(value, indent + 1)}`);
1072
+ }
1073
+ } else {
1074
+ const rendered = renderMarkdown(value, indent);
1075
+ if (first) {
1076
+ parts.push(`**${key}**: ${rendered}`);
1077
+ first = false;
1078
+ } else {
1079
+ parts.push(`${" ".repeat(indent)}**${key}**: ${rendered}`);
1080
+ }
1081
+ }
1082
+ }
1083
+ return parts.join("\n");
1084
+ }
1085
+ function renderObjectAsSection(obj, indent) {
1086
+ const entries = Object.entries(obj).filter(([k]) => k !== "_meta");
1087
+ if (entries.length === 0) return "(empty)";
1088
+ const lines = [];
1089
+ const headerLevel = Math.min(indent + 2, 6);
1090
+ const header = "#".repeat(headerLevel);
1091
+ for (const [key, value] of entries) {
1092
+ if (typeof value === "object" && value !== null) {
1093
+ lines.push(`${header} ${key}`);
1094
+ lines.push(renderMarkdown(value, indent + 1));
1095
+ } else {
1096
+ lines.push(`- **${key}**: ${renderMarkdown(value, indent)}`);
1097
+ }
1098
+ }
1099
+ return lines.join("\n");
1100
+ }
1101
+
1102
+ // src/adapters/langchain.ts
1103
+ var import_zod3 = require("zod");
1104
+ function typeRefToJsonSchema(typeRef, schema) {
1105
+ if (typeRef.kind === "NON_NULL") {
1106
+ if (!typeRef.ofType) return { type: "string" };
1107
+ return typeRefToJsonSchema(typeRef.ofType, schema);
1108
+ }
1109
+ if (typeRef.kind === "LIST") {
1110
+ if (!typeRef.ofType) return { type: "array", items: {} };
1111
+ return { type: "array", items: typeRefToJsonSchema(typeRef.ofType, schema) };
1112
+ }
1113
+ const unwrapped = unwrapType(typeRef);
1114
+ const typeName = unwrapped.name;
1115
+ if (typeName) {
1116
+ const namedType = schema.types.get(typeName);
1117
+ if (namedType && namedType.kind === "ENUM" && namedType.enumValues.length > 0) {
1118
+ return { type: "string", enum: namedType.enumValues.map((v) => v.name) };
1119
+ }
1120
+ if (namedType && namedType.kind === "INPUT_OBJECT") {
1121
+ const properties = {};
1122
+ const required = [];
1123
+ for (const field of namedType.inputFields) {
1124
+ properties[field.name] = typeRefToJsonSchema(field.type, schema);
1125
+ if (field.type.kind === "NON_NULL") {
1126
+ required.push(field.name);
1127
+ }
1128
+ }
1129
+ const result = { type: "object", properties };
1130
+ if (required.length > 0) result.required = required;
1131
+ return result;
1132
+ }
1133
+ }
1134
+ switch (typeName) {
1135
+ case "String":
1136
+ case "ID":
1137
+ return { type: "string" };
1138
+ case "Int":
1139
+ return { type: "integer" };
1140
+ case "Float":
1141
+ return { type: "number" };
1142
+ case "Boolean":
1143
+ return { type: "boolean" };
1144
+ default:
1145
+ return {};
1146
+ }
1147
+ }
1148
+ function typeRefToZod2(typeRef, schema) {
1149
+ if (typeRef.kind === "NON_NULL") {
1150
+ if (!typeRef.ofType) return import_zod3.z.unknown();
1151
+ return typeRefToZod2(typeRef.ofType, schema);
1152
+ }
1153
+ if (typeRef.kind === "LIST") {
1154
+ if (!typeRef.ofType) return import_zod3.z.array(import_zod3.z.unknown()).optional();
1155
+ return import_zod3.z.array(typeRefToZod2(typeRef.ofType, schema)).optional();
1156
+ }
1157
+ const unwrapped = unwrapType(typeRef);
1158
+ const typeName = unwrapped.name;
1159
+ if (typeName) {
1160
+ const namedType = schema.types.get(typeName);
1161
+ if (namedType && namedType.kind === "ENUM" && namedType.enumValues.length > 0) {
1162
+ const values = namedType.enumValues.map((v) => v.name);
1163
+ return import_zod3.z.enum(values).optional();
1164
+ }
1165
+ if (namedType && namedType.kind === "INPUT_OBJECT") {
1166
+ const shape = {};
1167
+ for (const field of namedType.inputFields) {
1168
+ const fieldSchema = typeRefToZod2(field.type, schema);
1169
+ if (field.type.kind === "NON_NULL") {
1170
+ shape[field.name] = fieldSchema;
1171
+ } else {
1172
+ shape[field.name] = fieldSchema.optional();
1173
+ }
1174
+ }
1175
+ return import_zod3.z.object(shape);
1176
+ }
1177
+ }
1178
+ switch (typeName) {
1179
+ case "String":
1180
+ case "ID":
1181
+ return import_zod3.z.string().optional();
1182
+ case "Int":
1183
+ return import_zod3.z.number().int().optional();
1184
+ case "Float":
1185
+ return import_zod3.z.number().optional();
1186
+ case "Boolean":
1187
+ return import_zod3.z.boolean().optional();
1188
+ default:
1189
+ return import_zod3.z.unknown().optional();
1190
+ }
1191
+ }
1192
+ function buildJsonSchema(field, schema) {
1193
+ const properties = {};
1194
+ const required = [];
1195
+ for (const arg of field.args) {
1196
+ properties[arg.name] = typeRefToJsonSchema(arg.type, schema);
1197
+ if (arg.type.kind === "NON_NULL") {
1198
+ required.push(arg.name);
1199
+ }
1200
+ }
1201
+ const result = {
1202
+ type: "object",
1203
+ properties
1204
+ };
1205
+ if (required.length > 0) result.required = required;
1206
+ return result;
1207
+ }
1208
+ function buildZodSchema(field, schema) {
1209
+ const shape = {};
1210
+ for (const arg of field.args) {
1211
+ const zodType = typeRefToZod2(arg.type, schema);
1212
+ if (arg.type.kind === "NON_NULL") {
1213
+ shape[arg.name] = zodType;
1214
+ } else {
1215
+ shape[arg.name] = zodType.optional();
1216
+ }
1217
+ }
1218
+ return import_zod3.z.object(shape);
1219
+ }
1220
+ function collectRootFields(schema) {
1221
+ const result = [];
1222
+ const queryType = schema.types.get(schema.queryType);
1223
+ if (queryType) {
1224
+ for (const field of queryType.fields) {
1225
+ result.push({ field, operationType: "query" });
1226
+ }
1227
+ }
1228
+ if (schema.mutationType) {
1229
+ const mutationType = schema.types.get(schema.mutationType);
1230
+ if (mutationType) {
1231
+ for (const field of mutationType.fields) {
1232
+ result.push({ field, operationType: "mutation" });
1233
+ }
1234
+ }
1235
+ }
1236
+ return result;
1237
+ }
1238
+ function createLangChainTools(schema, executor, options) {
1239
+ const maxDepth = options?.maxDepth ?? 2;
1240
+ const rootFields = collectRootFields(schema);
1241
+ return rootFields.map(({ field, operationType }) => {
1242
+ const toolName = operationType === "query" ? `query_${field.name}` : `mutate_${field.name}`;
1243
+ const description = field.description || `${operationType === "query" ? "Query" : "Mutation"} ${field.name}`;
1244
+ const jsonSchema = buildJsonSchema(field, schema);
1245
+ return {
1246
+ name: toolName,
1247
+ description,
1248
+ schema: jsonSchema,
1249
+ func: async (input) => {
1250
+ const variables = input ? JSON.parse(input) : {};
1251
+ const op = buildOperation(schema, field.name, { maxDepth });
1252
+ return executor.execute(op.operation, variables);
1253
+ }
1254
+ };
1255
+ });
1256
+ }
1257
+ function createStructuredTools(schema, executor, options) {
1258
+ const maxDepth = options?.maxDepth ?? 2;
1259
+ const rootFields = collectRootFields(schema);
1260
+ return rootFields.map(({ field, operationType }) => {
1261
+ const toolName = operationType === "query" ? `query_${field.name}` : `mutate_${field.name}`;
1262
+ const description = field.description || `${operationType === "query" ? "Query" : "Mutation"} ${field.name}`;
1263
+ const zodSchema = buildZodSchema(field, schema);
1264
+ return {
1265
+ name: toolName,
1266
+ description,
1267
+ schema: zodSchema,
1268
+ func: async (input) => {
1269
+ const op = buildOperation(schema, field.name, { maxDepth });
1270
+ return executor.execute(op.operation, input);
1271
+ }
1272
+ };
1273
+ });
1274
+ }
1275
+
1276
+ // src/adapters/crewai.ts
1277
+ function typeRefToJsonSchema2(typeRef, schema) {
1278
+ if (typeRef.kind === "NON_NULL") {
1279
+ if (!typeRef.ofType) return { type: "string" };
1280
+ return typeRefToJsonSchema2(typeRef.ofType, schema);
1281
+ }
1282
+ if (typeRef.kind === "LIST") {
1283
+ if (!typeRef.ofType) return { type: "array", items: {} };
1284
+ return { type: "array", items: typeRefToJsonSchema2(typeRef.ofType, schema) };
1285
+ }
1286
+ const unwrapped = unwrapType(typeRef);
1287
+ const typeName = unwrapped.name;
1288
+ if (typeName) {
1289
+ const namedType = schema.types.get(typeName);
1290
+ if (namedType && namedType.kind === "ENUM" && namedType.enumValues.length > 0) {
1291
+ return { type: "string", enum: namedType.enumValues.map((v) => v.name) };
1292
+ }
1293
+ if (namedType && namedType.kind === "INPUT_OBJECT") {
1294
+ const properties = {};
1295
+ const required = [];
1296
+ for (const field of namedType.inputFields) {
1297
+ properties[field.name] = typeRefToJsonSchema2(field.type, schema);
1298
+ if (field.type.kind === "NON_NULL") {
1299
+ required.push(field.name);
1300
+ }
1301
+ }
1302
+ const result = { type: "object", properties };
1303
+ if (required.length > 0) result.required = required;
1304
+ return result;
1305
+ }
1306
+ }
1307
+ switch (typeName) {
1308
+ case "String":
1309
+ case "ID":
1310
+ return { type: "string" };
1311
+ case "Int":
1312
+ return { type: "integer" };
1313
+ case "Float":
1314
+ return { type: "number" };
1315
+ case "Boolean":
1316
+ return { type: "boolean" };
1317
+ default:
1318
+ return {};
1319
+ }
1320
+ }
1321
+ function buildArgsSchema(field, schema) {
1322
+ const properties = {};
1323
+ const required = [];
1324
+ for (const arg of field.args) {
1325
+ properties[arg.name] = typeRefToJsonSchema2(arg.type, schema);
1326
+ if (arg.type.kind === "NON_NULL") {
1327
+ required.push(arg.name);
1328
+ }
1329
+ }
1330
+ const result = {
1331
+ type: "object",
1332
+ properties
1333
+ };
1334
+ if (required.length > 0) result.required = required;
1335
+ return result;
1336
+ }
1337
+ function createCrewAITools(schema, executor, options) {
1338
+ const maxDepth = options?.maxDepth ?? 2;
1339
+ const tools = [];
1340
+ const queryType = schema.types.get(schema.queryType);
1341
+ if (queryType) {
1342
+ for (const field of queryType.fields) {
1343
+ const toolName = `query_${field.name}`;
1344
+ const description = field.description || `Query ${field.name}`;
1345
+ const argsSchema = buildArgsSchema(field, schema);
1346
+ tools.push({
1347
+ name: toolName,
1348
+ description,
1349
+ args_schema: argsSchema,
1350
+ func: async (args) => {
1351
+ const op = buildOperation(schema, field.name, { maxDepth });
1352
+ return executor.execute(op.operation, args);
1353
+ }
1354
+ });
1355
+ }
1356
+ }
1357
+ if (schema.mutationType) {
1358
+ const mutationType = schema.types.get(schema.mutationType);
1359
+ if (mutationType) {
1360
+ for (const field of mutationType.fields) {
1361
+ const toolName = `mutate_${field.name}`;
1362
+ const description = field.description || `Mutation ${field.name}`;
1363
+ const argsSchema = buildArgsSchema(field, schema);
1364
+ tools.push({
1365
+ name: toolName,
1366
+ description,
1367
+ args_schema: argsSchema,
1368
+ func: async (args) => {
1369
+ const op = buildOperation(schema, field.name, { maxDepth });
1370
+ return executor.execute(op.operation, args);
1371
+ }
1372
+ });
1373
+ }
1374
+ }
1375
+ }
1376
+ return tools;
1377
+ }
1378
+
1379
+ // src/adapters/vercel-ai.ts
1380
+ var import_zod4 = require("zod");
1381
+ function typeRefToZod3(typeRef, schema) {
1382
+ if (typeRef.kind === "NON_NULL") {
1383
+ if (!typeRef.ofType) return import_zod4.z.unknown();
1384
+ return typeRefToZod3(typeRef.ofType, schema);
1385
+ }
1386
+ if (typeRef.kind === "LIST") {
1387
+ if (!typeRef.ofType) return import_zod4.z.array(import_zod4.z.unknown()).optional();
1388
+ return import_zod4.z.array(typeRefToZod3(typeRef.ofType, schema)).optional();
1389
+ }
1390
+ const unwrapped = unwrapType(typeRef);
1391
+ const typeName = unwrapped.name;
1392
+ if (typeName) {
1393
+ const namedType = schema.types.get(typeName);
1394
+ if (namedType && namedType.kind === "ENUM" && namedType.enumValues.length > 0) {
1395
+ const values = namedType.enumValues.map((v) => v.name);
1396
+ return import_zod4.z.enum(values).optional();
1397
+ }
1398
+ if (namedType && namedType.kind === "INPUT_OBJECT") {
1399
+ const shape = {};
1400
+ for (const field of namedType.inputFields) {
1401
+ const fieldSchema = typeRefToZod3(field.type, schema);
1402
+ if (field.type.kind === "NON_NULL") {
1403
+ shape[field.name] = fieldSchema;
1404
+ } else {
1405
+ shape[field.name] = fieldSchema.optional();
1406
+ }
1407
+ }
1408
+ return import_zod4.z.object(shape);
1409
+ }
1410
+ }
1411
+ switch (typeName) {
1412
+ case "String":
1413
+ case "ID":
1414
+ return import_zod4.z.string().optional();
1415
+ case "Int":
1416
+ return import_zod4.z.number().int().optional();
1417
+ case "Float":
1418
+ return import_zod4.z.number().optional();
1419
+ case "Boolean":
1420
+ return import_zod4.z.boolean().optional();
1421
+ default:
1422
+ return import_zod4.z.unknown().optional();
1423
+ }
1424
+ }
1425
+ function buildParametersSchema(field, schema) {
1426
+ const shape = {};
1427
+ for (const arg of field.args) {
1428
+ const zodType = typeRefToZod3(arg.type, schema);
1429
+ if (arg.type.kind === "NON_NULL") {
1430
+ shape[arg.name] = zodType;
1431
+ } else {
1432
+ shape[arg.name] = zodType.optional();
1433
+ }
1434
+ }
1435
+ return import_zod4.z.object(shape);
1436
+ }
1437
+ function createVercelAITools(schema, executor, options) {
1438
+ const maxDepth = options?.maxDepth ?? 2;
1439
+ const tools = {};
1440
+ const queryType = schema.types.get(schema.queryType);
1441
+ if (queryType) {
1442
+ for (const field of queryType.fields) {
1443
+ const toolName = `query_${field.name}`;
1444
+ const description = field.description || `Query ${field.name}`;
1445
+ const parameters = buildParametersSchema(field, schema);
1446
+ tools[toolName] = {
1447
+ description,
1448
+ parameters,
1449
+ execute: async (args) => {
1450
+ const op = buildOperation(schema, field.name, { maxDepth });
1451
+ return executor.execute(op.operation, args);
1452
+ }
1453
+ };
1454
+ }
1455
+ }
1456
+ if (schema.mutationType) {
1457
+ const mutationType = schema.types.get(schema.mutationType);
1458
+ if (mutationType) {
1459
+ for (const field of mutationType.fields) {
1460
+ const toolName = `mutate_${field.name}`;
1461
+ const description = field.description || `Mutation ${field.name}`;
1462
+ const parameters = buildParametersSchema(field, schema);
1463
+ tools[toolName] = {
1464
+ description,
1465
+ parameters,
1466
+ execute: async (args) => {
1467
+ const op = buildOperation(schema, field.name, { maxDepth });
1468
+ return executor.execute(op.operation, args);
1469
+ }
1470
+ };
1471
+ }
1472
+ }
1473
+ }
1474
+ return tools;
1475
+ }
1476
+
1477
+ // src/mock/generator.ts
1478
+ var DEFAULT_ARRAY_LENGTH = 3;
1479
+ var DEFAULT_MAX_DEPTH = 3;
1480
+ function hashString(str, seed = 0) {
1481
+ let hash = seed;
1482
+ for (let i = 0; i < str.length; i++) {
1483
+ const char = str.charCodeAt(i);
1484
+ hash = (hash << 5) - hash + char | 0;
1485
+ }
1486
+ return Math.abs(hash);
1487
+ }
1488
+ function parseMockDirective(description) {
1489
+ if (!description) return void 0;
1490
+ const match = description.match(/@mock\(([^)]+)\)/);
1491
+ if (!match) return void 0;
1492
+ const raw = match[1].trim();
1493
+ if (raw.startsWith('"') && raw.endsWith('"') || raw.startsWith("'") && raw.endsWith("'")) {
1494
+ return raw.slice(1, -1);
1495
+ }
1496
+ if (raw === "true") return true;
1497
+ if (raw === "false") return false;
1498
+ const num = Number(raw);
1499
+ if (!isNaN(num)) return num;
1500
+ return raw;
1501
+ }
1502
+ function generateScalar(typeName, fieldName, index, seed) {
1503
+ const hash = hashString(fieldName, seed);
1504
+ switch (typeName) {
1505
+ case "String":
1506
+ return `mock_${fieldName}`;
1507
+ case "Int":
1508
+ return hash % 1e3 + index;
1509
+ case "Float":
1510
+ return parseFloat((hash % 1e4 / 100 + index * 0.1).toFixed(2));
1511
+ case "Boolean":
1512
+ return index % 2 === 0;
1513
+ case "ID":
1514
+ return `id_${fieldName}_${index}`;
1515
+ default:
1516
+ return `mock_${typeName}_${fieldName}`;
1517
+ }
1518
+ }
1519
+ function generateMockData(schema, typeName, config) {
1520
+ const seed = config?.seed ?? 0;
1521
+ const arrayLength = config?.arrayLength ?? DEFAULT_ARRAY_LENGTH;
1522
+ const maxDepth = config?.maxDepth ?? DEFAULT_MAX_DEPTH;
1523
+ return generateForType(schema, typeName, 0, maxDepth, arrayLength, seed, 0, /* @__PURE__ */ new Set());
1524
+ }
1525
+ function generateForType(schema, typeName, depth, maxDepth, arrayLength, seed, index, visited) {
1526
+ const type = schema.types.get(typeName);
1527
+ if (!type || type.fields.length === 0) {
1528
+ return {};
1529
+ }
1530
+ const result = {};
1531
+ for (const field of type.fields) {
1532
+ const mockValue = parseMockDirective(field.description);
1533
+ if (mockValue !== void 0) {
1534
+ result[field.name] = mockValue;
1535
+ continue;
1536
+ }
1537
+ result[field.name] = generateForField(
1538
+ schema,
1539
+ field,
1540
+ depth,
1541
+ maxDepth,
1542
+ arrayLength,
1543
+ seed,
1544
+ index,
1545
+ visited
1546
+ );
1547
+ }
1548
+ return result;
1549
+ }
1550
+ function generateForField(schema, field, depth, maxDepth, arrayLength, seed, index, visited) {
1551
+ return generateForTypeRef(
1552
+ schema,
1553
+ field.type,
1554
+ field.name,
1555
+ depth,
1556
+ maxDepth,
1557
+ arrayLength,
1558
+ seed,
1559
+ index,
1560
+ visited
1561
+ );
1562
+ }
1563
+ function generateForTypeRef(schema, typeRef, fieldName, depth, maxDepth, arrayLength, seed, index, visited) {
1564
+ if (typeRef.kind === "NON_NULL") {
1565
+ if (!typeRef.ofType) return null;
1566
+ return generateForTypeRef(
1567
+ schema,
1568
+ typeRef.ofType,
1569
+ fieldName,
1570
+ depth,
1571
+ maxDepth,
1572
+ arrayLength,
1573
+ seed,
1574
+ index,
1575
+ visited
1576
+ );
1577
+ }
1578
+ if (typeRef.kind === "LIST") {
1579
+ if (!typeRef.ofType) return [];
1580
+ if (depth >= maxDepth) return [];
1581
+ const items = [];
1582
+ for (let i = 0; i < arrayLength; i++) {
1583
+ items.push(
1584
+ generateForTypeRef(
1585
+ schema,
1586
+ typeRef.ofType,
1587
+ fieldName,
1588
+ depth,
1589
+ maxDepth,
1590
+ arrayLength,
1591
+ seed,
1592
+ i,
1593
+ new Set(visited)
1594
+ )
1595
+ );
1596
+ }
1597
+ return items;
1598
+ }
1599
+ const unwrapped = unwrapType(typeRef);
1600
+ const resolvedTypeName = unwrapped.name;
1601
+ if (!resolvedTypeName) return null;
1602
+ const namedType = schema.types.get(resolvedTypeName);
1603
+ if (namedType && namedType.kind === "ENUM" && namedType.enumValues.length > 0) {
1604
+ return namedType.enumValues[0].name;
1605
+ }
1606
+ if (unwrapped.kind === "SCALAR" || namedType && namedType.kind === "SCALAR") {
1607
+ return generateScalar(resolvedTypeName, fieldName, index, seed);
1608
+ }
1609
+ if (depth >= maxDepth) {
1610
+ return null;
1611
+ }
1612
+ if (visited.has(resolvedTypeName)) {
1613
+ return null;
1614
+ }
1615
+ visited.add(resolvedTypeName);
1616
+ const result = generateForType(
1617
+ schema,
1618
+ resolvedTypeName,
1619
+ depth + 1,
1620
+ maxDepth,
1621
+ arrayLength,
1622
+ seed,
1623
+ index,
1624
+ new Set(visited)
1625
+ );
1626
+ visited.delete(resolvedTypeName);
1627
+ return result;
1628
+ }
1629
+ function createMockExecutor(schema, config) {
1630
+ const mockExecutor = Object.create(GraphQLExecutor.prototype);
1631
+ mockExecutor.execute = async (operation, _variables, _additionalHeaders) => {
1632
+ const rootFieldName = extractRootFieldName(operation);
1633
+ if (!rootFieldName) {
1634
+ return JSON.stringify({ data: null });
1635
+ }
1636
+ const returnTypeName = findReturnTypeName(schema, rootFieldName);
1637
+ if (!returnTypeName) {
1638
+ return JSON.stringify({ data: { [rootFieldName]: null } });
1639
+ }
1640
+ const returnType = schema.types.get(returnTypeName);
1641
+ if (!returnType || returnType.kind === "SCALAR") {
1642
+ const scalarValue = generateScalar(returnTypeName, rootFieldName, 0, config?.seed ?? 0);
1643
+ return JSON.stringify({ data: { [rootFieldName]: scalarValue } }, null, 2);
1644
+ }
1645
+ const isList = isListField(schema, rootFieldName);
1646
+ if (isList) {
1647
+ const arrayLength = config?.arrayLength ?? DEFAULT_ARRAY_LENGTH;
1648
+ const items = [];
1649
+ for (let i = 0; i < arrayLength; i++) {
1650
+ items.push(generateMockData(schema, returnTypeName, { ...config, seed: (config?.seed ?? 0) + i }));
1651
+ }
1652
+ return JSON.stringify({ data: { [rootFieldName]: items } }, null, 2);
1653
+ }
1654
+ const mockData = generateMockData(schema, returnTypeName, config);
1655
+ return JSON.stringify({ data: { [rootFieldName]: mockData } }, null, 2);
1656
+ };
1657
+ return mockExecutor;
1658
+ }
1659
+ function extractRootFieldName(operation) {
1660
+ const match = operation.match(/(?:query|mutation|subscription)\s+\w*[^{]*\{\s*(\w+)/);
1661
+ if (match) return match[1];
1662
+ const simpleMatch = operation.match(/\{\s*(\w+)/);
1663
+ return simpleMatch ? simpleMatch[1] : null;
1664
+ }
1665
+ function findReturnTypeName(schema, fieldName) {
1666
+ const queryType = schema.types.get(schema.queryType);
1667
+ if (queryType) {
1668
+ const field = queryType.fields.find((f) => f.name === fieldName);
1669
+ if (field) {
1670
+ const unwrapped = unwrapType(field.type);
1671
+ return unwrapped.name;
1672
+ }
1673
+ }
1674
+ if (schema.mutationType) {
1675
+ const mutationType = schema.types.get(schema.mutationType);
1676
+ if (mutationType) {
1677
+ const field = mutationType.fields.find((f) => f.name === fieldName);
1678
+ if (field) {
1679
+ const unwrapped = unwrapType(field.type);
1680
+ return unwrapped.name;
1681
+ }
1682
+ }
1683
+ }
1684
+ return null;
1685
+ }
1686
+ function isListField(schema, fieldName) {
1687
+ const queryType = schema.types.get(schema.queryType);
1688
+ if (queryType) {
1689
+ const field = queryType.fields.find((f) => f.name === fieldName);
1690
+ if (field) return isListTypeRef(field.type);
1691
+ }
1692
+ if (schema.mutationType) {
1693
+ const mutationType = schema.types.get(schema.mutationType);
1694
+ if (mutationType) {
1695
+ const field = mutationType.fields.find((f) => f.name === fieldName);
1696
+ if (field) return isListTypeRef(field.type);
1697
+ }
1698
+ }
1699
+ return false;
1700
+ }
1701
+ function isListTypeRef(typeRef) {
1702
+ if (typeRef.kind === "LIST") return true;
1703
+ if (typeRef.kind === "NON_NULL" && typeRef.ofType) return isListTypeRef(typeRef.ofType);
1704
+ return false;
1705
+ }
1706
+ // Annotate the CommonJS export names for ESM import in node:
1707
+ 0 && (module.exports = {
1708
+ GraphQLExecutor,
1709
+ SchemaNavigator,
1710
+ buildOperation,
1711
+ createAgentToolkitServer,
1712
+ createCrewAITools,
1713
+ createLangChainTools,
1714
+ createMockExecutor,
1715
+ createStructuredTools,
1716
+ createToolsFromSchema,
1717
+ createVercelAITools,
1718
+ detectPaginationStyle,
1719
+ executePaginated,
1720
+ fetchSchema,
1721
+ formatForLLM,
1722
+ generateMockData,
1723
+ parseSchema,
1724
+ summarizeResponse
1725
+ });
1726
+ //# sourceMappingURL=index.cjs.map