-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathplugin.ts
More file actions
1855 lines (1749 loc) · 63.4 KB
/
Copy pathplugin.ts
File metadata and controls
1855 lines (1749 loc) · 63.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { readFileSync, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
import type { GatewayPlugin, Logger } from '@graphql-hive/gateway-runtime';
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';
import { loadDocumentsSync } from '@graphql-tools/load';
import type { LangfuseClientParams } from '@langfuse/client';
import {
concatAST,
parse,
type DocumentNode,
type ExecutionResult,
type GraphQLSchema,
} from 'graphql';
import { isAsyncIterable, type FetchAPI } from 'graphql-yoga';
import {
resolveDescriptions,
resolveFieldDescriptions,
resolveProviders,
type DescriptionProvider,
type DescriptionProviderConfig,
type DescriptionProviderContext,
type ProviderRegistry,
} from './description-provider.js';
import type {
MCPGraphQLOperation,
MCPMethodHandler,
} from './method-handler.js';
import {
loadOperationsFromDocument,
parseInlineHeaderDirectives,
resolveOperation,
type ParsedOperation,
} from './operation-loader.js';
import {
builtInMethodNames,
dealiasArgs,
formatToolCallResult,
handleMCPRequest,
processExecutionResult,
type CustomMethodDispatchContext,
type JsonRpcRequest,
type MCPHandlerOptions,
} from './protocol.js';
import type { LangfuseGetPromptOptions } from './providers/langfuse.js';
import { ToolRegistry, type RegisteredTool } from './registry.js';
import type { PluginContext } from './types.js';
type Prettify<T> = { [K in keyof T]: T[K] } & {};
interface MCPToolCallContext {
jsonrpcId: number | string | null;
toolName: string;
args: Record<string, unknown>;
tool: RegisteredTool;
headers: Record<string, string>;
}
/** Inline source: the GraphQL query is provided directly as a string. */
type InlineMCPToolSource = {
type: 'inline';
/** The GraphQL operation source */
query: string;
};
/** Reference source: resolves a named operation from operationsPath or a specific file. */
type GraphQLMCPToolSource = {
type: 'graphql';
/** Name of the operation to resolve */
operationName: string;
/** Whether the operation is a query or mutation */
operationType: 'query' | 'mutation';
/** Optional path to a .graphql file containing the operation (overrides operationsPath) */
file?: string;
};
/** Defines how a tool's GraphQL operation is sourced, either inline or by reference to a named operation. */
export type MCPToolSource = InlineMCPToolSource | GraphQLMCPToolSource;
/** Behavioral hints for MCP clients about a tool's characteristics. */
export interface MCPToolAnnotations {
/** If true, the tool does not modify its environment and is safe to call with any arguments. Clients assume false when omitted */
readOnlyHint?: boolean;
/** If true, the tool may perform destructive updates; if false, only additive. Only meaningful when readOnlyHint is false. Clients assume true when omitted */
destructiveHint?: boolean;
/** If true, calling repeatedly with the same arguments has no additional effect. Only meaningful when readOnlyHint is false. Clients assume false when omitted */
idempotentHint?: boolean;
/** If true, the tool may interact with an "open world" of external entities; if false, its domain of interaction is closed. Clients assume true when omitted */
openWorldHint?: boolean;
}
/** Icon metadata for tools, resources, or the server itself. */
export interface MCPIcon {
/** Standard URI pointing to the icon resource (HTTP/HTTPS URL or data: URI with base64-encoded image) */
src: string;
/** MIME type override (e.g. "image/png", "image/svg+xml") */
mimeType?: string;
/** Sizes at which the icon can be used in WxH format (e.g. ["48x48", "96x96"] or ["any"] for scalable) */
sizes?: string[];
/** Design context: "light" or "dark" background. If omitted, icon works with any theme */
theme?: string;
}
/** Tool execution capability flags per the MCP spec. */
export interface MCPToolExecution {
/** Whether this tool supports task-augmented execution (default: "forbidden") */
taskSupport?: 'forbidden' | 'optional' | 'required';
}
/** Optional metadata overrides for a tool (description, title, annotations, icons, provider). */
export interface MCPToolOverrides {
/** Display title override */
title?: string;
/** Description override (takes precedence over directive and schema descriptions) */
description?: string;
/** Behavioral hints for clients */
annotations?: MCPToolAnnotations;
/** Icon URLs for client UIs */
icons?: MCPIcon[];
/** Task support configuration */
execution?: MCPToolExecution;
/** Opaque metadata passed through to clients */
_meta?: Record<string, unknown>;
/** Dynamic description provider config (e.g. Langfuse prompt). Takes highest precedence */
descriptionProvider?:
| {
/** Provider type identifier */
type: 'langfuse';
/** Langfuse prompt name to fetch */
prompt: string;
/** Specific prompt version to use (omit for latest) */
version?: number;
/** Additional Langfuse getPrompt() options (e.g. label, cacheTtlSeconds) */
options?: LangfuseGetPromptOptions;
}
| DescriptionProviderConfig;
}
/** Per-field overrides for a tool's input schema (descriptions, examples, defaults, aliases). */
export interface MCPInputOverrides {
/** JSON Schema overrides keyed by GraphQL variable name */
schema?: {
/** Per-variable overrides */
properties?: Record<
string,
{
/** Override the variable's description in the input schema */
description?: string;
/** Example values for the variable */
examples?: unknown[];
/** Default value for the variable */
default?: unknown;
/** Rename the variable in the MCP input schema (original name used internally for GraphQL) */
alias?: string;
/** Dynamic description provider config for this specific field */
descriptionProvider?: DescriptionProviderConfig;
/** Hide this variable from the MCP input schema. The variable can still be set via a preprocess hook (e.g. from HTTP headers). */
hidden?: boolean;
}
>;
};
}
/** MCP annotation fields shared by content items and resources. */
export interface MCPAnnotations {
/** Intended audience: "user", "assistant", or both */
audience?: Array<'user' | 'assistant'>;
/** Importance from 0.0 (least important, optional) to 1.0 (most important, effectively required) */
priority?: number;
/** ISO 8601 timestamp of last modification (e.g. "2025-01-12T15:00:58Z") */
lastModified?: string;
}
/** Annotations for content items in tool responses. */
export type MCPContentAnnotations = MCPAnnotations;
/** Annotations for resource entries. */
export type MCPResourceAnnotations = MCPAnnotations;
interface MCPResourceConfigBase {
/** Display name for the resource */
name: string;
/** Unique URI identifying this resource */
uri: string;
/** Optional display title */
title?: string;
/** Human-readable description */
description?: string;
/** MIME type (default: "text/plain") */
mimeType?: string;
/** Icon URLs for client UIs */
icons?: MCPIcon[];
/** Resource-level annotations (audience, priority) */
annotations?: MCPResourceAnnotations;
/** Dynamic description provider config */
descriptionProvider?: DescriptionProviderConfig;
}
/**
* Configuration for a static MCP resource. Exactly one content source must be provided:
* `text` (inline string), `file` (path to read at startup), or `blob` (inline base64).
*/
export type MCPResourceConfig = MCPResourceConfigBase &
(
| {
/** Inline text content */
text: string;
file?: never;
blob?: never;
}
| {
/** Path to a file to read at startup */
file: string;
text?: never;
blob?: never;
/** If true, read as binary (base64). If false, read as UTF-8 text. Defaults to auto-detect from mimeType */
binary?: boolean;
}
| {
/** Inline base64-encoded binary content */
blob: string;
text?: never;
file?: never;
}
);
/** Immutable resolved form of a resource after startup processing (file reading, base64 validation). */
export interface ResolvedResource {
/** Display name for the resource */
readonly name: string;
/** Unique URI identifying this resource */
readonly uri: string;
/** Optional display title */
readonly title?: string;
/** Human-readable description */
readonly description?: string;
/** Resolved MIME type */
readonly mimeType: string;
/** Content size in bytes */
readonly size: number;
/** Icon URLs for client UIs */
readonly icons?: MCPIcon[];
/** Resource-level annotations */
readonly annotations?: MCPResourceAnnotations;
/** Text content (mutually exclusive with blob) */
readonly text?: string;
/** Base64-encoded binary content (mutually exclusive with text) */
readonly blob?: string;
/** Dynamic description provider config */
readonly descriptionProvider?: DescriptionProviderConfig;
}
/** Return type for resource template handlers. Must provide either `text` or `blob` content. */
export type ResourceTemplateResult =
| {
/** Text content returned by the handler */
text: string;
blob?: never;
/** MIME type override for this response */
mimeType?: string;
}
| {
/** Base64-encoded binary content returned by the handler */
blob: string;
text?: never;
/** MIME type override for this response */
mimeType?: string;
};
/** Configuration for a dynamic MCP resource template with a URI pattern and handler function. */
export interface MCPResourceTemplateConfig {
/** URI template with `{param}` placeholders (e.g. "file://project/{path}") */
uriTemplate: string;
/** Display name for the template */
name: string;
/** Optional display title */
title?: string;
/** Human-readable description */
description?: string;
/** Default MIME type for resolved resources (default: "text/plain") */
mimeType?: string;
/** Icon URLs for client UIs */
icons?: MCPIcon[];
/** Resource-level annotations */
annotations?: MCPResourceAnnotations;
/** Dynamic description provider config */
descriptionProvider?: DescriptionProviderConfig;
/** Handler function called with extracted URI parameters to produce resource content */
handler: (
params: Record<string, string>,
) => ResourceTemplateResult | Promise<ResourceTemplateResult>;
}
/** Immutable resolved form of a resource template with compiled URI pattern. */
export interface ResolvedResourceTemplate {
/** Original URI template string */
readonly uriTemplate: string;
/** Display name for the template */
readonly name: string;
/** Optional display title */
readonly title?: string;
/** Human-readable description */
readonly description?: string;
/** Default MIME type for resolved resources */
readonly mimeType?: string;
/** Icon URLs for client UIs */
readonly icons?: MCPIcon[];
/** Resource-level annotations */
readonly annotations?: MCPResourceAnnotations;
/** Dynamic description provider config */
readonly descriptionProvider?: DescriptionProviderConfig;
/** Handler function called with extracted URI parameters */
readonly handler: MCPResourceTemplateConfig['handler'];
/** Compiled regex pattern from the URI template */
readonly pattern: RegExp;
/** Parameter names extracted from the URI template (in order) */
readonly paramNames: string[];
}
const VALID_PARAM_NAME = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
export function compileUriTemplate(template: string): {
pattern: RegExp;
paramNames: string[];
} {
// Validate balanced braces before processing
const openCount = (template.match(/\{/g) || []).length;
const closeCount = (template.match(/\}/g) || []).length;
if (openCount !== closeCount) {
throw new Error(
`Unbalanced braces in URI template "${template}". Found ${openCount} opening and ${closeCount} closing braces.`,
);
}
const paramNames: string[] = [];
const escaped = template.replace(
/\{([^}]+)\}|([^{]+)/g,
(_match, param, literal) => {
if (param) {
if (!VALID_PARAM_NAME.test(param)) {
throw new Error(
`Invalid parameter name "{${param}}" in URI template "${template}". ` +
`Parameter names must be valid identifiers (letters, digits, underscores).`,
);
}
if (paramNames.includes(param)) {
throw new Error(
`Duplicate parameter name "{${param}}" in URI template "${template}". ` +
`Each parameter name must be unique.`,
);
}
paramNames.push(param);
return `(?<${param}>[^/]+)`;
}
return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
},
);
return { pattern: new RegExp(`^${escaped}$`), paramNames };
}
/** Output extraction and schema configuration for a tool's GraphQL response. */
export interface MCPOutputOverrides {
/** Dot-notation path to extract from the GraphQL response data, e.g. "search.items" */
path?: string;
/** Set to false to suppress outputSchema in tools/list */
schema?: false;
/** Annotations to attach to content items in tool responses (audience, priority) */
contentAnnotations?: MCPContentAnnotations;
/** Per-field description providers for output schema fields, keyed by dot-path (e.g. "forecast.conditions") */
descriptionProviders?: Record<string, DescriptionProviderConfig>;
}
/** Context passed to preprocess/postprocess hooks with request metadata. */
export interface ToolHookContext {
/** Name of the tool being executed */
toolName: string;
/** All HTTP headers from the incoming MCP request */
headers: Record<string, string>;
/** The GraphQL operation source for this tool */
query: string;
}
/** Lifecycle hooks for intercepting or transforming tool execution. */
export interface MCPToolHooks {
/**
* Called before GraphQL execution. Receives de-aliased arguments
* (original GraphQL variable names, not MCP alias names).
* Return a non-undefined value to short-circuit execution and use that value as the tool result.
* Return undefined (or void) to continue with normal GraphQL execution.
* When preprocess short-circuits, postprocess is NOT called.
*
* To return a raw MCP result, return an object with a `content` array of MCP content items
* (each with `type: "text" | "image" | "audio" | "resource" | "resource_link"`). This will be passed through directly
* as the MCP response, allowing custom fields like `_meta` or `isError`.
*/
preprocess?: (
args: Record<string, unknown>,
context: ToolHookContext,
) => unknown | Promise<unknown>;
/**
* Called after GraphQL execution (and output.path extraction) to transform the result.
* Not called when preprocess short-circuits.
* When a postprocess hook is registered, the response uses text content
* instead of structuredContent since the hook may change the result shape.
*
* To return a raw MCP result, return an object with a `content` array of MCP content items
* (each with `type: "text" | "image" | "audio" | "resource" | "resource_link"`). This will be passed through directly
* as the MCP response, allowing custom fields like `_meta` or `isError`.
*/
postprocess?: (
result: unknown,
args: Record<string, unknown>,
context: ToolHookContext,
) => unknown | Promise<unknown>;
}
/** Configuration for a single MCP tool backed by a GraphQL operation. */
export interface MCPToolConfig {
/** Unique tool name exposed to MCP clients */
name: string;
/** How to resolve the GraphQL operation (inline query or reference to a named operation) */
source: MCPToolSource;
/** Metadata overrides (description, title, annotations, icons, description provider) */
tool?: MCPToolOverrides;
/** Per-field input schema overrides (descriptions, examples, defaults, aliases) */
input?: MCPInputOverrides;
/** Output extraction and schema configuration */
output?: MCPOutputOverrides;
/** Pre/post-process hooks for intercepting or transforming tool execution */
hooks?: MCPToolHooks;
}
/**
* A user-provided operations source that can load GraphQL documents at startup
* and optionally push live updates. The plugin handles parsing, tool registration,
* and registry rebuilds; the loader only fetches the raw GraphQL source strings.
*/
export interface MCPOperationsLoader {
/**
* Fetch the operations source as a raw GraphQL string (may contain one or more operations).
* Called once at startup. If this rejects, the plugin logs the error and proceeds
* without loader-sourced tools. Implement retry logic inside load() if you need
* automatic recovery.
*/
load(): Promise<string>;
/**
* Subscribe to live updates. Called once after the initial `load()` succeeds.
* Invoke `callback` with the full updated source whenever it changes.
* Optionally return a cleanup function to unsubscribe (called on plugin dispose).
*/
onUpdate?(callback: (source: string) => void): (() => void) | void;
}
/** Top-level configuration for the MCP plugin. Passed to {@link useMCP}. */
export interface MCPConfig {
/** Logger instance */
log?: Logger;
/** Server name reported in `initialize` responses */
name: string;
/** Server version reported in `initialize` responses (default: "1.0.0") */
version?: string;
/** Human-readable server title */
title?: string;
/** Human-readable server description */
description?: string;
/** Server icons for client UIs */
icons?: MCPIcon[];
/** Server website URL */
websiteUrl?: string;
/** Free-text instructions included in `initialize` responses for LLM context */
instructions?: string;
/** MCP protocol version to advertise (default: "2025-11-25") */
protocolVersion?: string;
/** HTTP path for the MCP endpoint (default: "/mcp") */
path?: string;
/** Path to a .graphql file or directory of .graphql files containing operations */
operationsPath?: string;
/** Raw GraphQL operations source string (alternative to operationsPath) */
operationsStr?: string;
/** Tool definitions. Each maps a tool name to a GraphQL operation */
tools?: MCPToolConfig[];
/** Static resource definitions served via resources/list and resources/read */
resources?: MCPResourceConfig[];
/** Dynamic resource templates with URI patterns and handler functions */
resourceTemplates?: MCPResourceTemplateConfig[];
/**
* Description provider instances or configuration (e.g. Langfuse or custom providers)
*
* Custom providers: pass a DescriptionProvider instance containing fetchDescription or a config object for a built-in provider
*/
providers?: {
/** Built-in Langfuse provider. Accepts LangfuseClientParams (publicKey, secretKey, baseUrl) plus optional defaults */
langfuse?: Prettify<
LangfuseClientParams & {
/** Default prompt.get() options applied to all Langfuse description lookups (e.g. { label: "production" }) */
defaults?: Prettify<Partial<LangfuseGetPromptOptions>>;
}
>;
} & {
[key: string]: DescriptionProvider | Record<string, unknown> | undefined;
};
/** Suppress outputSchema from all tools in tools/list responses */
suppressOutputSchema?: boolean;
/** Dynamic operations source. Loaded at startup; if `onUpdate` is provided, the plugin subscribes to live changes and rebuilds tools automatically. */
loader?: MCPOperationsLoader;
/**
* Custom JSON-RPC methods served from the MCP endpoint alongside the
* built-ins. Keys are method names (e.g. "graphql/query"); names that
* collide with built-in methods cause startup to fail.
*/
customMethods?: Record<string, MCPMethodHandler>;
/**
* Additional capability entries merged into the `initialize` response.
* Keys merge shallowly over the built-in advertisement; custom entries win.
*/
customCapabilities?: Record<string, unknown>;
}
/** Internal resolved form of a tool config after merging directive and explicit config sources. */
export interface ResolvedToolConfig {
/** Unique tool name */
name: string;
/** Resolved GraphQL operation source */
query: string;
/** Metadata overrides (merged from directive + config) */
tool?: MCPToolOverrides;
/** Per-field input schema overrides */
input?: MCPInputOverrides;
/** Output extraction and schema configuration */
output?: MCPOutputOverrides;
/** Pre/post-process hooks */
hooks?: MCPToolHooks;
/** Description from @mcpTool directive (lower priority than config/provider) */
directiveDescription?: string;
/** Description from a provider (highest priority, resolved at request time) */
providerDescription?: string;
/** Maps variable name to HTTP header name, from @mcpHeader directives */
headerMappings?: Record<string, string>;
/** Metadata from @mcpTool meta argument (shallow merged with config _meta; config wins on key conflicts) */
directiveMeta?: Record<string, unknown>;
}
/**
* Parse a directive descriptionProvider string into a DescriptionProviderConfig.
* Format: "type:prompt" or "type:prompt:version"
* Example: "langfuse:my_prompt" or "langfuse:my_prompt:3"
*/
function parseDescriptionProviderDirective(
value: string,
): DescriptionProviderConfig {
const parts = value.split(':');
if (parts.length < 2 || parts.length > 3 || !parts[0] || !parts[1]) {
throw new Error(
`Invalid descriptionProvider directive format: "${value}". Expected "type:prompt" or "type:prompt:version" (e.g., "langfuse:my_prompt" or "langfuse:my_prompt:3")`,
);
}
const [type, prompt, versionStr] = parts;
if (parts.length === 3 && !versionStr) {
throw new Error(
`Invalid descriptionProvider directive format: "${value}". Trailing colon with no version. Expected "type:prompt" or "type:prompt:version".`,
);
}
const config: DescriptionProviderConfig = { type, prompt };
if (versionStr) {
const version = Number(versionStr);
if (!Number.isInteger(version) || version < 1) {
throw new Error(
`Invalid version "${versionStr}" in descriptionProvider directive "${value}". Version must be a positive integer.`,
);
}
config['version'] = version;
}
return config;
}
interface ResolveToolConfigsInput {
tools: MCPToolConfig[];
operationsSource?: DocumentNode;
}
export function resolveToolConfigs(
ctx: PluginContext,
input: ResolveToolConfigsInput,
): ResolvedToolConfig[] {
const { tools, operationsSource } = input;
let parsedOps: ParsedOperation[] | undefined;
if (operationsSource) {
parsedOps = loadOperationsFromDocument(ctx, operationsSource);
}
// build base configs from @mcpTool directives
const directiveTools = new Map();
if (parsedOps) {
for (const op of parsedOps) {
if (!op.mcpDirective) continue;
const toolOverrides: MCPToolOverrides = {};
if (op.mcpDirective.title) toolOverrides.title = op.mcpDirective.title;
if (op.mcpDirective.descriptionProvider) {
toolOverrides.descriptionProvider = parseDescriptionProviderDirective(
op.mcpDirective.descriptionProvider,
);
}
let directiveInput: MCPInputOverrides | undefined;
if (op.fieldDescriptionProviders) {
const properties: Record<
string,
{ descriptionProvider: DescriptionProviderConfig }
> = {};
for (const [varName, providerStr] of Object.entries(
op.fieldDescriptionProviders,
)) {
properties[varName] = {
descriptionProvider: parseDescriptionProviderDirective(providerStr),
};
}
directiveInput = { schema: { properties } };
}
let directiveOutput: MCPOutputOverrides | undefined;
if (op.selectionDescriptionProviders) {
const descriptionProviders: Record<string, DescriptionProviderConfig> =
{};
for (const [path, providerStr] of Object.entries(
op.selectionDescriptionProviders,
)) {
descriptionProviders[path] =
parseDescriptionProviderDirective(providerStr);
}
directiveOutput = { descriptionProviders };
}
directiveTools.set(op.mcpDirective.name, {
name: op.mcpDirective.name,
query: op.document,
directiveDescription: op.mcpDirective.description,
directiveMeta: op.mcpDirective.meta,
tool: Object.keys(toolOverrides).length > 0 ? toolOverrides : undefined,
input: directiveInput,
output: directiveOutput,
headerMappings: op.headerMappings,
});
}
}
// process explicit tools[] entries
const configTools = new Map();
for (const tool of tools) {
const { source } = tool;
let query: string;
let headerMappings: Record<string, string> | undefined;
if (source.type === 'inline') {
let parsed;
try {
parsed = parseInlineHeaderDirectives(ctx, source.query);
} catch (err) {
throw new Error(
`Tool "${tool.name}": failed to parse inline query: ${err instanceof Error ? err.message : String(err)}`,
);
}
query = parsed.query;
headerMappings = parsed.headerMappings;
} else {
let opsPool: ParsedOperation[];
if (source.file) {
let fileSource: string;
try {
fileSource = readFileSync(resolve(source.file), 'utf-8');
} catch (err) {
throw new Error(
`Tool "${tool.name}": cannot read operations file "${source.file}": ${err instanceof Error ? err.message : String(err)}`,
);
}
opsPool = loadOperationsFromDocument(ctx, parse(fileSource));
} else {
opsPool = parsedOps || [];
}
const op = resolveOperation(
opsPool,
source.operationName,
source.operationType,
);
if (!op) {
throw new Error(
`Operation "${source.operationName}" (${source.operationType}) not found in loaded operations for tool "${tool.name}"`,
);
}
query = op.document;
if (op.headerMappings) {
headerMappings = op.headerMappings;
}
}
configTools.set(tool.name, {
name: tool.name,
query,
tool: tool.tool,
input: tool.input,
output: tool.output,
hooks: tool.hooks,
headerMappings,
});
}
// merge: directive tools as base, config tools overlay (config wins for non-description fields)
const merged = new Map<string, ResolvedToolConfig>(directiveTools);
for (const [name, configTool] of configTools) {
const base = merged.get(name);
if (base) {
merged.set(name, {
name,
query: configTool.query,
directiveDescription: base.directiveDescription,
directiveMeta: base.directiveMeta,
tool: {
...base.tool,
...configTool.tool,
},
input: configTool.input || base.input,
output: configTool.output || base.output,
hooks: configTool.hooks || base.hooks,
headerMappings: configTool.headerMappings || base.headerMappings,
});
} else {
merged.set(name, configTool);
}
}
return Array.from(merged.values());
}
const TEXT_MIME_PREFIXES = ['text/'];
const TEXT_MIME_TYPES = new Set([
'application/json',
'application/xml',
'application/javascript',
'application/typescript',
'application/graphql',
'application/yaml',
'application/toml',
'application/xhtml+xml',
'application/svg+xml',
'application/x-sh',
]);
export function isTextMimeType(mimeType: string): boolean {
if (TEXT_MIME_PREFIXES.some((p) => mimeType.startsWith(p))) return true;
return TEXT_MIME_TYPES.has(mimeType);
}
export function resolveResources(
ctx: PluginContext,
configs: MCPResourceConfig[],
): Map<string, ResolvedResource> {
const map = new Map<string, ResolvedResource>();
for (const cfg of configs) {
// Runtime validation for JSON/YAML config that bypasses TypeScript's discriminated union
const raw = cfg as {
name: string;
uri: string;
text?: string;
file?: string;
blob?: string;
};
const sourceCount =
(raw.text != null ? 1 : 0) +
(raw.file != null ? 1 : 0) +
(raw.blob != null ? 1 : 0);
if (sourceCount > 1) {
throw new Error(
`Resource "${raw.name}" (${raw.uri}): specify exactly one of "text", "file", or "blob"`,
);
}
if (sourceCount === 0) {
throw new Error(
`Resource "${raw.name}" (${raw.uri}): must specify either "text", "file", or "blob"`,
);
}
if (map.has(cfg.uri)) {
throw new Error(
`Duplicate resource URI "${cfg.uri}" (resource "${cfg.name}")`,
);
}
const mimeType = cfg.mimeType || 'text/plain';
let text: string | undefined;
let blob: string | undefined;
let size: number;
if ('blob' in cfg && cfg.blob != null) {
// Inline base64 — decode to validate and get accurate size
const decoded = Buffer.from(cfg.blob, 'base64');
if (decoded.toString('base64') !== cfg.blob) {
throw new Error(
`Resource "${cfg.name}" (${cfg.uri}): "blob" field contains invalid base64 encoding`,
);
}
blob = cfg.blob;
size = decoded.length;
} else if ('file' in cfg && cfg.file != null) {
// File: detect text vs binary from mimeType (overridable with binary flag)
const filePath = resolve(cfg.file);
const isBinary =
cfg.binary !== undefined ? cfg.binary : !isTextMimeType(mimeType);
try {
if (isBinary) {
const buf = readFileSync(filePath);
blob = buf.toString('base64');
size = buf.length;
} else {
text = readFileSync(filePath, 'utf-8');
size = Buffer.byteLength(text);
}
} catch (err) {
throw new Error(
`Resource "${cfg.name}" (${cfg.uri}): cannot read file "${cfg.file}": ${err instanceof Error ? err.message : String(err)}`,
);
}
if (size === 0) {
ctx.log.warn(
`Resource "${cfg.name}" (${cfg.uri}): file "${cfg.file}" is empty (0 bytes)`,
);
}
} else {
// Inline text
text = (cfg as { text: string }).text;
size = Buffer.byteLength(text);
}
map.set(cfg.uri, {
name: cfg.name,
uri: cfg.uri,
title: cfg.title,
description: cfg.description,
mimeType,
size,
icons: cfg.icons,
annotations: cfg.annotations,
text,
blob,
descriptionProvider: cfg.descriptionProvider,
});
}
return map;
}
export function resolveResourceTemplates(
configs: MCPResourceTemplateConfig[],
): ResolvedResourceTemplate[] {
return configs.map((cfg) => {
const { pattern, paramNames } = compileUriTemplate(cfg.uriTemplate);
return {
uriTemplate: cfg.uriTemplate,
name: cfg.name,
title: cfg.title,
description: cfg.description,
mimeType: cfg.mimeType,
icons: cfg.icons,
annotations: cfg.annotations,
descriptionProvider: cfg.descriptionProvider,
handler: cfg.handler,
pattern,
paramNames,
};
});
}
function loadOperationsSource(config: MCPConfig): DocumentNode | undefined {
if (!config.operationsPath) return undefined;
const opsPath = resolve(config.operationsPath);
let pointer = config.operationsPath;
try {
if (statSync(opsPath).isDirectory()) {
pointer = join(opsPath, '**/*.graphql');
}
} catch {
// Let loadDocumentsSync handle the error for non-existent paths
}
let sources;
try {
sources = loadDocumentsSync(pointer, {
loaders: [new GraphQLFileLoader()],
});
} catch {
throw new Error(`No .graphql files found at "${config.operationsPath}"`);
}
const documents = sources.map((s) => {
if (!s.document) {
throw new Error(
`Failed to parse "${s.location ?? config.operationsPath}": no document produced`,
);
}
return s.document;
});
return concatAST(documents);
}
/**
* Create a Gateway plugin that exposes GraphQL operations as MCP tools.
* Handles the full MCP protocol (initialize, tools/list, tools/call, resources)
* by routing tool calls through the Yoga GraphQL pipeline.
*/
export function useMCP(ctx: PluginContext, config: MCPConfig): GatewayPlugin {
if (!config.name?.trim()) {
throw new Error(
'[MCP] config.name is required and must be a non-empty string',
);
}
if (config.tools != null && !Array.isArray(config.tools)) {
throw new Error(
'[MCP] config.tools must be an array of tool configurations',
);
}
if (config.customMethods) {
const conflicts = Object.keys(config.customMethods).filter((name) =>
builtInMethodNames.has(name),
);
if (conflicts.length > 0) {
throw new Error(
`[MCP] customMethods cannot override built-in methods: ${conflicts.join(', ')}. ` +
`Built-in methods are: ${[...builtInMethodNames].join(', ')}`,
);
}
for (const [name, handler] of Object.entries(config.customMethods)) {
if (typeof handler !== 'function') {
throw new Error(`[MCP] customMethods["${name}"] must be a function`);
}
}
}
const mcpPath = config.path || '/mcp';
let registry: ToolRegistry | null = null;
let schema: GraphQLSchema | null = null;
let executeViaYoga:
| ((
operation: MCPGraphQLOperation,
headers: Record<string, string>,
serverContext: unknown,
) => Promise<ExecutionResult>)
| null = null;
ctx = { ...ctx, log: (config.log ?? ctx.log).child('[MCP] ') };
const logger = ctx.log;
// Resolve operations from files at startup
const operationsSource = config.operationsStr
? parse(config.operationsStr)
: loadOperationsSource(config);
let resolvedTools = resolveToolConfigs(ctx, {
tools: config.tools || [],
operationsSource,
});
// Dynamic operations loader: async init + live updates.
// If load() fails, the error is logged and no retry is attempted.
// The plugin continues without loader-sourced tools.
let loaderInitPromise: Promise<void> | null = null;
let loaderCleanup: (() => void) | void | null = null;
let loaderDisposed = false;
function rebuildToolsFromLoader(source: string) {
let loaderDoc: DocumentNode;
try {
loaderDoc = parse(source);
} catch (err) {
logger.error(
`Failed to parse loader operations. Keeping previous tools.`,
err instanceof Error ? err.message : err,
);
return;
}
const mergedDoc = operationsSource
? concatAST([loaderDoc, operationsSource])
: loaderDoc;
let newResolvedTools: ResolvedToolConfig[];
try {
newResolvedTools = resolveToolConfigs(ctx, {
tools: config.tools || [],
operationsSource: mergedDoc,
});
} catch (err) {
logger.error(
`Failed to resolve loader operations. Keeping previous tools.`,
err instanceof Error ? err.message : err,
);
return;
}
if (schema) {
const previousTools = resolvedTools;
try {
const newRegistry = new ToolRegistry(ctx, newResolvedTools, schema);
resolvedTools = newResolvedTools;
const newOptions = buildHandlerOptions(newRegistry);
registry = newRegistry;
mcpHandlerOptions = newOptions;