import { Logger } from '@graphql-hive/logger';
import { DisposableSymbols } from '@whatwg-node/disposablestack';
import { MaybePromise } from '@whatwg-node/promise-helpers';
import { ExecutionRequest, ExecutionResult, Executor, MaybePromise as MaybePromise$1, Maybe } from '@graphql-tools/utils';
import { GraphQLSchema, OperationTypeNode, GraphQLFieldResolver, GraphQLResolveInfo, GraphQLOutputType, GraphQLError, SelectionSetNode, FragmentDefinitionNode, FieldNode, ExecutionResult as ExecutionResult$1, SelectionNode } from 'graphql';
import DataLoader from 'dataloader';
import { GraphQLResolveInfo as GraphQLResolveInfo$1, GraphQLOutputType as GraphQLOutputType$1 } from 'graphql/type';
import { Plugin, YogaInitialContext, Instrumentation as Instrumentation$2 } from 'graphql-yoga';
import { MeshFetch, KeyValueCache, MeshFetchRequestInit, Logger as Logger$1 } from '@graphql-mesh/types';
import { FetchInstrumentation } from '@graphql-mesh/utils';
import { PromptManager, LangfuseClient, LangfuseClientParams } from '@langfuse/client';

type TopicDataMap = {
    [topic: string]: any;
};
type PubSubListener<Data extends TopicDataMap, Topic extends keyof Data> = (data: Data[Topic]) => void;
interface PubSub<M extends TopicDataMap = TopicDataMap> {
    /**
     * Publish {@link data} for a {@link topic}.
     * @returns `void` or a `Promise` that resolves when the data has been successfully published
     */
    publish<Topic extends keyof M>(topic: Topic, data: M[Topic]): MaybePromise<void>;
    /**
     * A distinct list of all topics that are currently subscribed to.
     * Can be a promise to accomodate distributed systems where subscribers exist on other
     * locations and we need to know about all of them.
     */
    subscribedTopics(): MaybePromise<Iterable<keyof M>>;
    /**
     * Subscribe and listen to a {@link topic} receiving its data.
     *
     * If the {@link listener} is provided, it will be called whenever data is emitted for the {@link topic},
     *
     * @returns an unsubscribe function or a `Promise<unsubscribe function>` that resolves when the subscription is successfully established. the unsubscribe function returns `void` or a `Promise` that resolves on successful unsubscribe and subscription cleanup
     *
     * If the {@link listener} is not provided,
     *
     * @returns an `AsyncIterable` that yields data for the given {@link topic}
     */
    subscribe<Topic extends keyof M>(topic: Topic): AsyncIterable<M[Topic]>;
    subscribe<Topic extends keyof M>(topic: Topic, listener: PubSubListener<M, Topic>): MaybePromise<() => MaybePromise<void>>;
    /**
     * Closes active subscriptions and disposes of all resources. Publishing and subscribing after disposal
     * is not possible and will throw an error if attempted.
     */
    dispose(): MaybePromise<void>;
    /** @see {@link dispose} */
    [DisposableSymbols.asyncDispose](): Promise<void>;
}

interface TransportEntry<Options extends Record<string, any> = Record<string, any>> {
    kind: string;
    subgraph: string;
    location?: string;
    headers?: [string, string][];
    options?: Options;
}

type SchemaTransform<TContext = Record<any, string>> = (originalWrappingSchema: GraphQLSchema, subschemaConfig: SubschemaConfig<any, any, any, TContext>) => GraphQLSchema;
type RequestTransform<T = Record<string, any>, TContext = Record<any, string>> = (originalRequest: ExecutionRequest, delegationContext: DelegationContext<TContext>, transformationContext: T) => ExecutionRequest;
type ResultTransform<T = Record<string, any>, TContext = Record<any, string>> = (originalResult: ExecutionResult, delegationContext: DelegationContext<TContext>, transformationContext: T) => ExecutionResult;
interface Transform<T = any, TContext = Record<string, any>> {
    transformSchema?: SchemaTransform<TContext>;
    transformRequest?: RequestTransform<T, TContext>;
    transformResult?: ResultTransform<T, TContext>;
}
interface DelegationContext<TContext = Record<string, any>> {
    subschema: GraphQLSchema | SubschemaConfig<any, any, any, TContext>;
    subschemaConfig?: SubschemaConfig<any, any, any, TContext>;
    targetSchema: GraphQLSchema;
    operation: OperationTypeNode;
    fieldName: string;
    args?: Record<string, any>;
    context?: TContext;
    info?: GraphQLResolveInfo;
    returnType: GraphQLOutputType;
    onLocatedError?: (originalError: GraphQLError) => GraphQLError;
    rootValue?: any;
    transforms: Array<Transform<any, TContext>>;
    transformedSchema: GraphQLSchema;
    skipTypeMerging: boolean;
}
type DelegationPlanBuilder = (schema: GraphQLSchema, sourceSubschema: Subschema<any, any, any, any>, variableValues: Record<string, any>, fragments: Record<string, FragmentDefinitionNode>, fieldNodes: FieldNode[], context?: any, info?: GraphQLResolveInfo) => Array<Map<Subschema, SelectionSetNode>>;
interface ICreateProxyingResolverOptions<TContext = Record<string, any>> {
    subschemaConfig: SubschemaConfig<any, any, any, TContext>;
    operation?: OperationTypeNode;
    fieldName?: string;
}
type CreateProxyingResolverFn<TContext = Record<string, any>> = (options: ICreateProxyingResolverOptions<TContext>) => GraphQLFieldResolver<any, TContext>;
interface BatchingOptions<K = any, V = any, C = K> {
    extensionsReducer?: (mergedExtensions: Record<string, any>, request: ExecutionRequest) => Record<string, any>;
    dataLoaderOptions?: DataLoader.Options<K, V, C>;
}
interface SubschemaConfig<K = any, V = any, C = K, TContext = Record<string, any>> {
    name?: string;
    schema: GraphQLSchema;
    createProxyingResolver?: CreateProxyingResolverFn<TContext>;
    rootValue?: any;
    transforms?: Array<Transform<any, TContext>>;
    merge?: Record<string, MergedTypeConfig<any, any, TContext>>;
    executor?: Executor<TContext>;
    batch?: boolean;
    batchingOptions?: BatchingOptions<K, V, C>;
}
interface MergedTypeConfig<K = any, V = any, TContext = Record<string, any>> extends MergedTypeEntryPoint<K, V, TContext> {
    entryPoints?: Array<MergedTypeEntryPoint>;
    fields?: Record<string, MergedFieldConfig>;
    canonical?: boolean;
}
interface MergedTypeEntryPoint<K = any, V = any, TContext = Record<string, any>> extends MergedTypeResolverOptions<K, V> {
    selectionSet?: string;
    key?: (originalResult: any) => K | PromiseLike<K>;
    resolve?: MergedTypeResolver<TContext>;
}
interface MergedTypeResolverOptions<K = any, V = any> {
    fieldName?: string;
    args?: (originalResult: any) => Record<string, any>;
    argsFromKeys?: (keys: ReadonlyArray<K>) => Record<string, any>;
    valuesFromResults?: (results: any, keys: ReadonlyArray<K>) => Array<V>;
    dataLoaderOptions?: DataLoader.Options<K, V>;
}
type OverrideHandler = (context: any, info: GraphQLResolveInfo) => boolean;
interface MergedFieldConfig {
    selectionSet?: string;
    computed?: boolean;
    canonical?: boolean;
    provides?: SelectionSetNode;
    override?: OverrideHandler;
}
type MergedTypeResolver<TContext = Record<string, any>> = (originalResult: any, context: TContext, info: GraphQLResolveInfo, subschema: Subschema<any, any, any, TContext>, selectionSet: SelectionSetNode, key: any | undefined, type: GraphQLOutputType) => any;

interface ISubschema<K = any, V = any, C = K, TContext = Record<string, any>> extends SubschemaConfig<K, V, C, TContext> {
    transformedSchema: GraphQLSchema;
}
declare class Subschema<K = any, V = any, C = K, TContext = Record<string, any>> implements ISubschema<K, V, C, TContext> {
    name?: string;
    schema: GraphQLSchema;
    executor?: Executor<TContext>;
    batch?: boolean;
    batchingOptions?: BatchingOptions<K, V, C>;
    createProxyingResolver?: CreateProxyingResolverFn<TContext>;
    transforms: Array<Transform<any, TContext>>;
    private _transformedSchema;
    merge?: Record<string, MergedTypeConfig<any, any, TContext>>;
    constructor(config: SubschemaConfig<K, V, C, TContext>);
    get transformedSchema(): GraphQLSchema;
    set transformedSchema(value: GraphQLSchema);
}

type Instrumentation$1 = {
    /**
     * Wrap each subgraph execution request. This can happen multiple time for the same graphql operation.
     */
    subgraphExecute?: (payload: {
        executionRequest: ExecutionRequest;
        subgraphName: string;
    }, wrapped: () => MaybePromise<void>) => MaybePromise<void>;
    /**
     * Wrap each supergraph schema loading.
     *
     * Note: this span is only available when an Async compatible context manager is available
     */
    schema?: (payload: null, wrapped: () => MaybePromise<void>) => MaybePromise<void>;
};

declare module 'graphql' {
    interface GraphQLResolveInfo {
        executionRequest?: ExecutionRequest;
    }
}
interface UnifiedGraphPlugin<TContext> {
    onSubgraphExecute?: OnSubgraphExecuteHook<TContext>;
    onDelegationPlan?: OnDelegationPlanHook<TContext>;
    onDelegationStageExecute?: OnDelegationStageExecuteHook<TContext>;
}
type OnSubgraphExecuteHook<TContext = any> = (payload: OnSubgraphExecutePayload<TContext>) => MaybePromise$1<Maybe<OnSubgraphExecuteDoneHook | void>>;
interface OnSubgraphExecutePayload<TContext> {
    subgraph: GraphQLSchema;
    subgraphName: string;
    transportEntry?: TransportEntry;
    executionRequest: ExecutionRequest<any, TContext>;
    setExecutionRequest(executionRequest: ExecutionRequest): void;
    executor: Executor;
    setExecutor(executor: Executor): void;
    log: Logger;
}
interface OnSubgraphExecuteDonePayload {
    result: AsyncIterable<ExecutionResult$1> | ExecutionResult$1;
    setResult(result: AsyncIterable<ExecutionResult$1> | ExecutionResult$1): void;
}
type OnSubgraphExecuteDoneHook = (payload: OnSubgraphExecuteDonePayload) => MaybePromise$1<Maybe<OnSubgraphExecuteDoneResult | void>>;
type OnSubgraphExecuteDoneResultOnNext = (payload: OnSubgraphExecuteDoneOnNextPayload) => MaybePromise$1<void>;
interface OnSubgraphExecuteDoneOnNextPayload {
    result: ExecutionResult$1;
    setResult(result: ExecutionResult$1): void;
}
type OnSubgraphExecuteDoneResultOnEnd = () => MaybePromise$1<void>;
type OnSubgraphExecuteDoneResult = {
    onNext?: OnSubgraphExecuteDoneResultOnNext;
    onEnd?: OnSubgraphExecuteDoneResultOnEnd;
};
type OnDelegationPlanHook<TContext> = (payload: OnDelegationPlanHookPayload<TContext>) => Maybe<OnDelegationPlanDoneHook | void>;
interface OnDelegationPlanHookPayload<TContext> {
    supergraph: GraphQLSchema;
    subgraph: string;
    sourceSubschema: Subschema<any, any, any, TContext>;
    typeName: string;
    variables: Record<string, any>;
    fragments: Record<string, FragmentDefinitionNode>;
    fieldNodes: SelectionNode[];
    context: TContext;
    log: Logger;
    info?: GraphQLResolveInfo$1;
    delegationPlanBuilder: DelegationPlanBuilder;
    setDelegationPlanBuilder(delegationPlanBuilder: DelegationPlanBuilder): void;
}
type OnDelegationPlanDoneHook = (payload: OnDelegationPlanDonePayload) => Maybe<void>;
interface OnDelegationPlanDonePayload {
    delegationPlan: ReturnType<DelegationPlanBuilder>;
    setDelegationPlan: (delegationPlan: ReturnType<DelegationPlanBuilder>) => void;
}
type OnDelegationStageExecuteHook<TContext> = (payload: OnDelegationStageExecutePayload<TContext>) => Maybe<OnDelegationStageExecuteDoneHook>;
interface OnDelegationStageExecutePayload<TContext> {
    object: any;
    context: TContext;
    info: GraphQLResolveInfo$1;
    subgraph: string;
    subschema: Subschema<any, any, any, TContext>;
    selectionSet: SelectionSetNode;
    key?: any;
    type: GraphQLOutputType$1;
    resolver: MergedTypeResolver<TContext>;
    setResolver: (resolver: MergedTypeResolver<TContext>) => void;
    typeName: string;
    log: Logger;
}
type OnDelegationStageExecuteDoneHook = (payload: OnDelegationStageExecuteDonePayload) => void;
interface OnDelegationStageExecuteDonePayload {
    result: any;
    setResult: (result: any) => void;
}

interface GatewayConfigContext {
    /**
     * WHATWG compatible Fetch implementation.
     */
    fetch: MeshFetch;
    /**
     * The logger to use throught Hive and its plugins.
     */
    log: Logger;
    /**
     * Current working directory.
     * Note that working directory does not exist in serverless environments and will therefore be empty.
     */
    cwd: string;
    /**
     * Event bus for pub/sub.
     */
    pubsub?: PubSub;
    /**
     * Cache Storage
     */
    cache?: KeyValueCache;
}
interface GatewayContext extends GatewayConfigContext, YogaInitialContext {
    /**
     * Environment agnostic HTTP headers provided with the request.
     */
    headers: Record<string, string>;
    /**
     * Runtime context available within WebSocket connections.
     */
    connectionParams?: Record<string, string>;
}
type GatewayPlugin<TPluginContext extends Record<string, any> = Record<string, any>, TContext extends Record<string, any> = Record<string, any>> = Plugin<Partial<TPluginContext> & GatewayContext & TContext, GatewayConfigContext> & UnifiedGraphPlugin<Partial<TPluginContext> & GatewayContext & TContext> & {
    onFetch?: OnFetchHook<Partial<TPluginContext> & TContext>;
    onCacheGet?: OnCacheGetHook;
    onCacheSet?: OnCacheSetHook;
    onCacheDelete?: OnCacheDeleteHook;
    /**
     * An Instrumentation instance that will wrap each phases of the request pipeline.
     * This should be used primarily as an observability tool (for monitoring, tracing, etc...).
     *
     * Note: The wrapped functions in instrumentation should always be called. Use hooks to
     *       conditionally skip a phase.
     */
    instrumentation?: Instrumentation<TPluginContext & TContext & GatewayContext>;
};
interface OnFetchHookPayload<TContext> {
    url: string;
    setURL(url: URL | string): void;
    options: MeshFetchRequestInit;
    setOptions(options: MeshFetchRequestInit): void;
    /**
     * The context is not available in cases where "fetch" is done in
     * order to pull a supergraph or do some internal work.
     *
     * The logger will be available in all cases.
     */
    context: (GatewayContext & TContext) | {
        log: Logger;
    };
    /** @deprecated Please use `log` from the {@link context} instead. */
    logger: Logger$1;
    info: GraphQLResolveInfo$1;
    fetchFn: MeshFetch;
    setFetchFn: (fetchFn: MeshFetch) => void;
    executionRequest?: ExecutionRequest;
    endResponse: (response$: MaybePromise$1<Response>) => void;
}
interface OnFetchHookDonePayload {
    response: Response;
    setResponse: (response: Response) => void;
}
type OnFetchHookDone = (payload: OnFetchHookDonePayload) => MaybePromise$1<void>;
type OnFetchHook<TContext> = (payload: OnFetchHookPayload<TContext>) => MaybePromise$1<void | OnFetchHookDone>;
type OnCacheGetHook = (payload: OnCacheGetHookEventPayload) => MaybePromise$1<OnCacheGetHookResult | void>;
interface OnCacheGetHookEventPayload {
    cache: KeyValueCache;
    key: string;
    ttl?: number;
}
interface OnCacheGetHookResult {
    onCacheHit?: OnCacheHitHook;
    onCacheMiss?: OnCacheMissHook;
    onCacheGetError?: OnCacheErrorHook;
}
type OnCacheErrorHook = (payload: OnCacheErrorHookPayload) => void;
interface OnCacheErrorHookPayload {
    error: Error;
}
type OnCacheHitHook = (payload: OnCacheHitHookEventPayload) => void;
interface OnCacheHitHookEventPayload {
    value: any;
}
type OnCacheMissHook = () => void;
type OnCacheSetHook = (payload: OnCacheSetHookEventPayload) => MaybePromise$1<OnCacheSetHookResult | void>;
interface OnCacheSetHookResult {
    onCacheSetDone?: () => void;
    onCacheSetError?: OnCacheErrorHook;
}
interface OnCacheSetHookEventPayload {
    cache: KeyValueCache;
    key: string;
    value: any;
    ttl?: number;
}
type OnCacheDeleteHook = (payload: OnCacheDeleteHookEventPayload) => MaybePromise$1<OnCacheDeleteHookResult | void>;
interface OnCacheDeleteHookResult {
    onCacheDeleteDone?: () => void;
    onCacheDeleteError?: OnCacheErrorHook;
}
interface OnCacheDeleteHookEventPayload {
    cache: KeyValueCache;
    key: string;
}
type Instrumentation<TContext extends Record<string, any>> = Instrumentation$2<TContext> & Instrumentation$1 & FetchInstrumentation;

interface PluginContext {
    log: Logger;
    fetch?: typeof fetch | MeshFetch;
}

/** Configuration object for a description provider, identified by `type` with provider-specific fields. */
interface DescriptionProviderConfig {
    /** Provider type identifier (e.g. "langfuse") */
    type: string;
    /** Provider-specific configuration fields */
    [key: string]: unknown;
}
/** Request-scoped context passed to description providers (e.g. prompt label for A/B testing). */
interface DescriptionProviderContext {
    /** Prompt label for selecting provider variants (e.g. "production", "staging") */
    label?: string;
}
/** Interface for custom description providers that dynamically resolve tool/resource descriptions. */
interface DescriptionProvider {
    /**
     * Fetch a description for a tool or resource.
     * @param toolName - The name of the tool or resource
     * @param config - Provider-specific configuration from the tool/resource definition
     * @param context - Optional request-scoped context (e.g. prompt label)
     * @returns The resolved description string
     */
    fetchDescription(toolName: string, config: DescriptionProviderConfig, context?: DescriptionProviderContext): Promise<string>;
}

/** Options type for text prompt retrieval via `PromptManager.get()`, derived from the Langfuse SDK. */
type LangfuseGetPromptOptions = NonNullable<Parameters<{
    get(name: string, options?: PromptManager extends {
        get(name: string, options?: infer TextOpts): Promise<any>;
        get(...args: any[]): any;
    } ? TextOpts : never): any;
}['get']>[1]>;
/** Create a description provider backed by Langfuse prompt management. */
declare function createLangfuseProvider(client: LangfuseClient, defaults?: Partial<LangfuseGetPromptOptions>): DescriptionProvider;

type Prettify<T> = {
    [K in keyof T]: T[K];
} & {};
/** 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. */
type MCPToolSource = InlineMCPToolSource | GraphQLMCPToolSource;
/** Behavioral hints for MCP clients about a tool's characteristics. */
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. */
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. */
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). */
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). */
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. */
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. */
type MCPContentAnnotations = MCPAnnotations;
/** Annotations for resource entries. */
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).
 */
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). */
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. */
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. */
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. */
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[];
}
/** Output extraction and schema configuration for a tool's GraphQL response. */
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. */
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. */
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. */
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.
 */
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}. */
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;
}
/** Internal resolved form of a tool config after merging directive and explicit config sources. */
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>;
}
/**
 * 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.
 */
declare function useMCP(ctx: PluginContext, config: MCPConfig): GatewayPlugin;

export { type DescriptionProvider, type DescriptionProviderConfig, type DescriptionProviderContext, type MCPAnnotations, type MCPConfig, type MCPContentAnnotations, type MCPIcon, type MCPInputOverrides, type MCPOperationsLoader, type MCPOutputOverrides, type MCPResourceAnnotations, type MCPResourceConfig, type MCPResourceTemplateConfig, type MCPToolAnnotations, type MCPToolConfig, type MCPToolExecution, type MCPToolHooks, type MCPToolOverrides, type MCPToolSource, type ResolvedResource, type ResolvedResourceTemplate, type ResolvedToolConfig, type ResourceTemplateResult, type ToolHookContext, createLangfuseProvider, useMCP };
