UNPKG

ai

Version:

AI SDK by Vercel - The AI Toolkit for TypeScript and JavaScript

1,475 lines (1,396 loc) 171 kB
import { IDGenerator } from '@ai-sdk/provider-utils'; export { CoreToolCall, CoreToolResult, IDGenerator, ToolCall, ToolResult, createIdGenerator, generateId } from '@ai-sdk/provider-utils'; import { DataStreamString, Message, Schema, DeepPartial, JSONValue as JSONValue$1, AssistantMessage, DataMessage } from '@ai-sdk/ui-utils'; export { AssistantMessage, AssistantStatus, Attachment, ChatRequest, ChatRequestOptions, CreateMessage, DataMessage, DataStreamPart, DeepPartial, IdGenerator, JSONValue, Message, RequestOptions, Schema, ToolInvocation, UIMessage, UseAssistantOptions, formatAssistantStreamPart, formatDataStreamPart, jsonSchema, parseAssistantStreamPart, parseDataStreamPart, processDataStream, processTextStream, zodSchema } from '@ai-sdk/ui-utils'; import { LanguageModelV1, LanguageModelV1FinishReason, LanguageModelV1LogProbs, LanguageModelV1CallWarning, LanguageModelV1Source, JSONValue, EmbeddingModelV1, EmbeddingModelV1Embedding, ImageModelV1, ImageModelV1CallWarning, LanguageModelV1ProviderMetadata, TranscriptionModelV1, TranscriptionModelV1CallWarning, SpeechModelV1, SpeechModelV1CallWarning, LanguageModelV1CallOptions, AISDKError, LanguageModelV1FunctionToolCall, JSONSchema7, JSONParseError, TypeValidationError, ProviderV1, NoSuchModelError } from '@ai-sdk/provider'; export { AISDKError, APICallError, EmptyResponseBodyError, InvalidPromptError, InvalidResponseDataError, JSONParseError, LanguageModelV1, LanguageModelV1CallOptions, LanguageModelV1Prompt, LanguageModelV1StreamPart, LoadAPIKeyError, NoContentGeneratedError, NoSuchModelError, TypeValidationError, UnsupportedFunctionalityError } from '@ai-sdk/provider'; import { ServerResponse } from 'node:http'; import { AttributeValue, Tracer } from '@opentelemetry/api'; import { z } from 'zod'; import { ServerResponse as ServerResponse$1 } from 'http'; /** Language model that is used by the AI SDK Core functions. */ type LanguageModel = LanguageModelV1; /** Reason why a language model finished generating a response. Can be one of the following: - `stop`: model generated stop sequence - `length`: model generated maximum number of tokens - `content-filter`: content filter violation stopped the model - `tool-calls`: model triggered tool calls - `error`: model stopped because of an error - `other`: model stopped for other reasons */ type FinishReason = LanguageModelV1FinishReason; /** Log probabilities for each token and its top log probabilities. @deprecated Will become a provider extension in the future. */ type LogProbs = LanguageModelV1LogProbs; /** Warning from the model provider for this call. The call will proceed, but e.g. some settings might not be supported, which can lead to suboptimal results. */ type CallWarning = LanguageModelV1CallWarning; /** A source that has been used as input to generate the response. */ type Source = LanguageModelV1Source; /** Tool choice for the generation. It supports the following settings: - `auto` (default): the model can choose whether and which tools to call. - `required`: the model must call a tool. It can choose which tool to call. - `none`: the model must not call tools - `{ type: 'tool', toolName: string (typed) }`: the model must call the specified tool */ type ToolChoice<TOOLS extends Record<string, unknown>> = 'auto' | 'none' | 'required' | { type: 'tool'; toolName: keyof TOOLS; }; /** * @deprecated Use `ToolChoice` instead. */ type CoreToolChoice<TOOLS extends Record<string, unknown>> = ToolChoice<TOOLS>; interface DataStreamWriter { /** * Appends a data part to the stream. */ write(data: DataStreamString): void; /** * Appends a data part to the stream. */ writeData(value: JSONValue): void; /** * Appends a message annotation to the stream. */ writeMessageAnnotation(value: JSONValue): void; /** * Appends a source part to the stream. */ writeSource(source: Source): void; /** * Merges the contents of another stream to this stream. */ merge(stream: ReadableStream<DataStreamString>): void; /** * Error handler that is used by the data stream writer. * This is intended for forwarding when merging streams * to prevent duplicated error masking. */ onError: ((error: unknown) => string) | undefined; } declare function createDataStream({ execute, onError, }: { execute: (dataStream: DataStreamWriter) => Promise<void> | void; onError?: (error: unknown) => string; }): ReadableStream<DataStreamString>; declare function createDataStreamResponse({ status, statusText, headers, execute, onError, }: ResponseInit & { execute: (dataStream: DataStreamWriter) => Promise<void> | void; onError?: (error: unknown) => string; }): Response; declare function pipeDataStreamToResponse(response: ServerResponse, { status, statusText, headers, execute, onError, }: ResponseInit & { execute: (writer: DataStreamWriter) => Promise<void> | void; onError?: (error: unknown) => string; }): void; /** * Telemetry configuration. */ type TelemetrySettings = { /** * Enable or disable telemetry. Disabled by default while experimental. */ isEnabled?: boolean; /** * Enable or disable input recording. Enabled by default. * * You might want to disable input recording to avoid recording sensitive * information, to reduce data transfers, or to increase performance. */ recordInputs?: boolean; /** * Enable or disable output recording. Enabled by default. * * You might want to disable output recording to avoid recording sensitive * information, to reduce data transfers, or to increase performance. */ recordOutputs?: boolean; /** * Identifier for this function. Used to group telemetry data by function. */ functionId?: string; /** * Additional information to include in the telemetry data. */ metadata?: Record<string, AttributeValue>; /** * A custom tracer to use for the telemetry data. */ tracer?: Tracer; }; /** Embedding model that is used by the AI SDK Core functions. */ type EmbeddingModel<VALUE> = EmbeddingModelV1<VALUE>; /** Embedding. */ type Embedding = EmbeddingModelV1Embedding; /** Image model that is used by the AI SDK Core functions. */ type ImageModel = ImageModelV1; /** Warning from the model provider for this call. The call will proceed, but e.g. some settings might not be supported, which can lead to suboptimal results. */ type ImageGenerationWarning = ImageModelV1CallWarning; type ImageModelResponseMetadata = { /** Timestamp for the start of the generated response. */ timestamp: Date; /** The ID of the response model that was used to generate the response. */ modelId: string; /** Response headers. */ headers?: Record<string, string>; }; type LanguageModelRequestMetadata = { /** Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified). */ body?: string; }; type LanguageModelResponseMetadata = { /** ID for the generated response. */ id: string; /** Timestamp for the start of the generated response. */ timestamp: Date; /** The ID of the response model that was used to generate the response. */ modelId: string; /** Response headers (available only for providers that use HTTP requests). */ headers?: Record<string, string>; }; /** * Provider for language, text embedding, and image models. */ type Provider = { /** Returns the language model with the given id. The model id is then passed to the provider function to get the model. @param {string} id - The id of the model to return. @returns {LanguageModel} The language model associated with the id @throws {NoSuchModelError} If no such model exists. */ languageModel(modelId: string): LanguageModel; /** Returns the text embedding model with the given id. The model id is then passed to the provider function to get the model. @param {string} id - The id of the model to return. @returns {LanguageModel} The language model associated with the id @throws {NoSuchModelError} If no such model exists. */ textEmbeddingModel(modelId: string): EmbeddingModel<string>; /** Returns the image model with the given id. The model id is then passed to the provider function to get the model. @param {string} id - The id of the model to return. @returns {ImageModel} The image model associated with the id */ imageModel(modelId: string): ImageModel; }; /** Additional provider-specific metadata that is returned from the provider. This is needed to enable provider-specific functionality that can be fully encapsulated in the provider. */ type ProviderMetadata = LanguageModelV1ProviderMetadata; /** Additional provider-specific options. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ type ProviderOptions = LanguageModelV1ProviderMetadata; /** Represents the number of tokens used in a prompt and completion. */ type LanguageModelUsage = { /** The number of tokens used in the prompt. */ promptTokens: number; /** The number of tokens used in the completion. */ completionTokens: number; /** The total number of tokens used (promptTokens + completionTokens). */ totalTokens: number; }; /** Represents the number of tokens used in an embedding. */ type EmbeddingModelUsage = { /** The number of tokens used in the embedding. */ tokens: number; }; /** Transcription model that is used by the AI SDK Core functions. */ type TranscriptionModel = TranscriptionModelV1; /** Warning from the model provider for this call. The call will proceed, but e.g. some settings might not be supported, which can lead to suboptimal results. */ type TranscriptionWarning = TranscriptionModelV1CallWarning; type TranscriptionModelResponseMetadata = { /** Timestamp for the start of the generated response. */ timestamp: Date; /** The ID of the response model that was used to generate the response. */ modelId: string; /** Response headers. */ headers?: Record<string, string>; }; /** Speech model that is used by the AI SDK Core functions. */ type SpeechModel = SpeechModelV1; /** Warning from the model provider for this call. The call will proceed, but e.g. some settings might not be supported, which can lead to suboptimal results. */ type SpeechWarning = SpeechModelV1CallWarning; type SpeechModelResponseMetadata = { /** Timestamp for the start of the generated response. */ timestamp: Date; /** The ID of the response model that was used to generate the response. */ modelId: string; /** Response headers. */ headers?: Record<string, string>; }; /** The result of an `embed` call. It contains the embedding, the value, and additional information. */ interface EmbedResult<VALUE> { /** The value that was embedded. */ readonly value: VALUE; /** The embedding of the value. */ readonly embedding: Embedding; /** The embedding token usage. */ readonly usage: EmbeddingModelUsage; /** Optional raw response data. */ readonly rawResponse?: { /** Response headers. */ headers?: Record<string, string>; }; } /** Embed a value using an embedding model. The type of the value is defined by the embedding model. @param model - The embedding model to use. @param value - The value that should be embedded. @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. @param abortSignal - An optional abort signal that can be used to cancel the call. @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. @returns A result object that contains the embedding, the value, and additional information. */ declare function embed<VALUE>({ model, value, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry, }: { /** The embedding model to use. */ model: EmbeddingModel<VALUE>; /** The value that should be embedded. */ value: VALUE; /** Maximum number of retries per embedding model call. Set to 0 to disable retries. @default 2 */ maxRetries?: number; /** Abort signal. */ abortSignal?: AbortSignal; /** Additional headers to include in the request. Only applicable for HTTP-based providers. */ headers?: Record<string, string>; /** * Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; }): Promise<EmbedResult<VALUE>>; /** The result of a `embedMany` call. It contains the embeddings, the values, and additional information. */ interface EmbedManyResult<VALUE> { /** The values that were embedded. */ readonly values: Array<VALUE>; /** The embeddings. They are in the same order as the values. */ readonly embeddings: Array<Embedding>; /** The embedding token usage. */ readonly usage: EmbeddingModelUsage; } /** Embed several values using an embedding model. The type of the value is defined by the embedding model. `embedMany` automatically splits large requests into smaller chunks if the model has a limit on how many embeddings can be generated in a single call. @param model - The embedding model to use. @param values - The values that should be embedded. @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. @param abortSignal - An optional abort signal that can be used to cancel the call. @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. @returns A result object that contains the embeddings, the value, and additional information. */ declare function embedMany<VALUE>({ model, values, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry, }: { /** The embedding model to use. */ model: EmbeddingModel<VALUE>; /** The values that should be embedded. */ values: Array<VALUE>; /** Maximum number of retries per embedding model call. Set to 0 to disable retries. @default 2 */ maxRetries?: number; /** Abort signal. */ abortSignal?: AbortSignal; /** Additional headers to include in the request. Only applicable for HTTP-based providers. */ headers?: Record<string, string>; /** * Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; }): Promise<EmbedManyResult<VALUE>>; type CallSettings = { /** Maximum number of tokens to generate. */ maxTokens?: number; /** Temperature setting. This is a number between 0 (almost no randomness) and 1 (very random). It is recommended to set either `temperature` or `topP`, but not both. @default 0 */ temperature?: number; /** Nucleus sampling. This is a number between 0 and 1. E.g. 0.1 would mean that only tokens with the top 10% probability mass are considered. It is recommended to set either `temperature` or `topP`, but not both. */ topP?: number; /** Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Recommended for advanced use cases only. You usually only need to use temperature. */ topK?: number; /** Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt. The presence penalty is a number between -1 (increase repetition) and 1 (maximum penalty, decrease repetition). 0 means no penalty. */ presencePenalty?: number; /** Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. The frequency penalty is a number between -1 (increase repetition) and 1 (maximum penalty, decrease repetition). 0 means no penalty. */ frequencyPenalty?: number; /** Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated. Providers may have limits on the number of stop sequences. */ stopSequences?: string[]; /** The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results. */ seed?: number; /** Maximum number of retries. Set to 0 to disable retries. @default 2 */ maxRetries?: number; /** Abort signal. */ abortSignal?: AbortSignal; /** Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. */ headers?: Record<string, string | undefined>; }; /** Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer. */ type DataContent = string | Uint8Array | ArrayBuffer | Buffer; type ToolResultContent = Array<{ type: 'text'; text: string; } | { type: 'image'; data: string; mimeType?: string; }>; /** Text content part of a prompt. It contains a string of text. */ interface TextPart { type: 'text'; /** The text content. */ text: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; } /** Image content part of a prompt. It contains an image. */ interface ImagePart { type: 'image'; /** Image data. Can either be: - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer - URL: a URL that points to the image */ image: DataContent | URL; /** Optional mime type of the image. */ mimeType?: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; } /** File content part of a prompt. It contains a file. */ interface FilePart { type: 'file'; /** File data. Can either be: - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer - URL: a URL that points to the image */ data: DataContent | URL; /** Optional filename of the file. */ filename?: string; /** Mime type of the file. */ mimeType: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; } /** * Reasoning content part of a prompt. It contains a reasoning. */ interface ReasoningPart { type: 'reasoning'; /** The reasoning text. */ text: string; /** An optional signature for verifying that the reasoning originated from the model. */ signature?: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; } /** Redacted reasoning content part of a prompt. */ interface RedactedReasoningPart { type: 'redacted-reasoning'; /** Redacted reasoning data. */ data: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; } /** Tool call content part of a prompt. It contains a tool call (usually generated by the AI model). */ interface ToolCallPart { type: 'tool-call'; /** ID of the tool call. This ID is used to match the tool call with the tool result. */ toolCallId: string; /** Name of the tool that is being called. */ toolName: string; /** Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema. */ args: unknown; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; } /** Tool result content part of a prompt. It contains the result of the tool call with the matching ID. */ interface ToolResultPart { type: 'tool-result'; /** ID of the tool call that this result is associated with. */ toolCallId: string; /** Name of the tool that generated this result. */ toolName: string; /** Result of the tool call. This is a JSON-serializable object. */ result: unknown; /** Multi-part content of the tool result. Only for tools that support multipart results. */ experimental_content?: ToolResultContent; /** Optional flag if the result is an error or an error message. */ isError?: boolean; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; } /** A system message. It can contain system information. Note: using the "system" part of the prompt is strongly preferred to increase the resilience against prompt injection attacks, and because not all providers support several system messages. */ type CoreSystemMessage = { role: 'system'; content: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; }; declare const coreSystemMessageSchema: z.ZodType<CoreSystemMessage>; /** A user message. It can contain text or a combination of text and images. */ type CoreUserMessage = { role: 'user'; content: UserContent; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; }; declare const coreUserMessageSchema: z.ZodType<CoreUserMessage>; /** Content of a user message. It can be a string or an array of text and image parts. */ type UserContent = string | Array<TextPart | ImagePart | FilePart>; /** An assistant message. It can contain text, tool calls, or a combination of text and tool calls. */ type CoreAssistantMessage = { role: 'assistant'; content: AssistantContent; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; }; declare const coreAssistantMessageSchema: z.ZodType<CoreAssistantMessage>; /** Content of an assistant message. It can be a string or an array of text, image, reasoning, redacted reasoning, and tool call parts. */ type AssistantContent = string | Array<TextPart | FilePart | ReasoningPart | RedactedReasoningPart | ToolCallPart>; /** A tool message. It contains the result of one or more tool calls. */ type CoreToolMessage = { role: 'tool'; content: ToolContent; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** @deprecated Use `providerOptions` instead. */ experimental_providerMetadata?: ProviderMetadata; }; declare const coreToolMessageSchema: z.ZodType<CoreToolMessage>; /** Content of a tool message. It is an array of tool result parts. */ type ToolContent = Array<ToolResultPart>; /** A message that can be used in the `messages` field of a prompt. It can be a user message, an assistant message, or a tool message. */ type CoreMessage = CoreSystemMessage | CoreUserMessage | CoreAssistantMessage | CoreToolMessage; declare const coreMessageSchema: z.ZodType<CoreMessage>; /** Prompt part of the AI function options. It contains a system message, a simple text prompt, or a list of messages. */ type Prompt = { /** System message to include in the prompt. Can be used with `prompt` or `messages`. */ system?: string; /** A simple text prompt. You can either use `prompt` or `messages` but not both. */ prompt?: string; /** A list of messages. You can either use `prompt` or `messages` but not both. */ messages?: Array<CoreMessage> | Array<Omit<Message, 'id'>>; }; /** * A generated file. */ interface GeneratedFile { /** File as a base64 encoded string. */ readonly base64: string; /** File as a Uint8Array. */ readonly uint8Array: Uint8Array; /** MIME type of the file */ readonly mimeType: string; } type ReasoningDetail = { type: 'text'; text: string; signature?: string; } | { type: 'redacted'; data: string; }; type ToolParameters = z.ZodTypeAny | Schema<any>; type inferParameters<PARAMETERS extends ToolParameters> = PARAMETERS extends Schema<any> ? PARAMETERS['_type'] : PARAMETERS extends z.ZodTypeAny ? z.infer<PARAMETERS> : never; interface ToolExecutionOptions { /** * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data. */ toolCallId: string; /** * Messages that were sent to the language model to initiate the response that contained the tool call. * The messages **do not** include the system prompt nor the assistant response that contained the tool call. */ messages: CoreMessage[]; /** * An optional abort signal that indicates that the overall operation should be aborted. */ abortSignal?: AbortSignal; } /** A tool contains the description and the schema of the input that the tool expects. This enables the language model to generate the input. The tool can also contain an optional execute function for the actual execution function of the tool. */ type Tool<PARAMETERS extends ToolParameters = any, RESULT = any> = { /** The schema of the input that the tool expects. The language model will use this to generate the input. It is also used to validate the output of the language model. Use descriptions to make the input understandable for the language model. */ parameters: PARAMETERS; /** An optional description of what the tool does. Will be used by the language model to decide whether to use the tool. Not used for provider-defined tools. */ description?: string; /** Optional conversion function that maps the tool result to multi-part tool content for LLMs. */ experimental_toToolResultContent?: (result: RESULT) => ToolResultContent; /** An async function that is called with the arguments from the tool call and produces a result. If not provided, the tool will not be executed automatically. @args is the input of the tool call. @options.abortSignal is a signal that can be used to abort the tool call. */ execute?: (args: inferParameters<PARAMETERS>, options: ToolExecutionOptions) => PromiseLike<RESULT>; } & ({ /** Function tool. */ type?: undefined | 'function'; } | { /** Provider-defined tool. */ type: 'provider-defined'; /** The ID of the tool. Should follow the format `<provider-name>.<tool-name>`. */ id: `${string}.${string}`; /** The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record<string, unknown>; }); /** * @deprecated Use `Tool` instead. */ type CoreTool<PARAMETERS extends ToolParameters = any, RESULT = any> = Tool<PARAMETERS, RESULT>; /** Helper function for inferring the execute args of a tool. */ declare function tool<PARAMETERS extends ToolParameters, RESULT>(tool: Tool<PARAMETERS, RESULT> & { execute: (args: inferParameters<PARAMETERS>, options: ToolExecutionOptions) => PromiseLike<RESULT>; }): Tool<PARAMETERS, RESULT> & { execute: (args: inferParameters<PARAMETERS>, options: ToolExecutionOptions) => PromiseLike<RESULT>; }; declare function tool<PARAMETERS extends ToolParameters, RESULT>(tool: Tool<PARAMETERS, RESULT> & { execute?: undefined; }): Tool<PARAMETERS, RESULT> & { execute: undefined; }; /** Create a union of the given object's values, and optionally specify which keys to get the values from. Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript. @example ``` // data.json { 'foo': 1, 'bar': 2, 'biz': 3 } // main.ts import type {ValueOf} from 'type-fest'; import data = require('./data.json'); export function getData(name: string): ValueOf<typeof data> { return data[name]; } export function onlyBar(name: string): ValueOf<typeof data, 'bar'> { return data[name]; } // file.ts import {getData, onlyBar} from './main'; getData('foo'); //=> 1 onlyBar('foo'); //=> TypeError ... onlyBar('bar'); //=> 2 ``` * @see https://github.com/sindresorhus/type-fest/blob/main/source/value-of.d.ts */ type ValueOf<ObjectType, ValueType extends keyof ObjectType = keyof ObjectType> = ObjectType[ValueType]; declare const JSONRPCRequestSchema: z.ZodObject<z.objectUtil.extendShape<{ jsonrpc: z.ZodLiteral<"2.0">; id: z.ZodUnion<[z.ZodString, z.ZodNumber]>; }, { method: z.ZodString; params: z.ZodOptional<z.ZodObject<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">>>; }>, "strict", z.ZodTypeAny, { id: string | number; method: string; jsonrpc: "2.0"; params?: z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }, { id: string | number; method: string; jsonrpc: "2.0"; params?: z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }>; type JSONRPCRequest = z.infer<typeof JSONRPCRequestSchema>; declare const JSONRPCResponseSchema: z.ZodObject<{ jsonrpc: z.ZodLiteral<"2.0">; id: z.ZodUnion<[z.ZodString, z.ZodNumber]>; result: z.ZodObject<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">>; }, "strict", z.ZodTypeAny, { result: { _meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined; } & { [k: string]: unknown; }; id: string | number; jsonrpc: "2.0"; }, { result: { _meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined; } & { [k: string]: unknown; }; id: string | number; jsonrpc: "2.0"; }>; type JSONRPCResponse = z.infer<typeof JSONRPCResponseSchema>; declare const JSONRPCErrorSchema: z.ZodObject<{ jsonrpc: z.ZodLiteral<"2.0">; id: z.ZodUnion<[z.ZodString, z.ZodNumber]>; error: z.ZodObject<{ code: z.ZodNumber; message: z.ZodString; data: z.ZodOptional<z.ZodUnknown>; }, "strip", z.ZodTypeAny, { code: number; message: string; data?: unknown; }, { code: number; message: string; data?: unknown; }>; }, "strict", z.ZodTypeAny, { error: { code: number; message: string; data?: unknown; }; id: string | number; jsonrpc: "2.0"; }, { error: { code: number; message: string; data?: unknown; }; id: string | number; jsonrpc: "2.0"; }>; type JSONRPCError = z.infer<typeof JSONRPCErrorSchema>; declare const JSONRPCNotificationSchema: z.ZodObject<z.objectUtil.extendShape<{ jsonrpc: z.ZodLiteral<"2.0">; }, { method: z.ZodString; params: z.ZodOptional<z.ZodObject<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">>>; }>, "strict", z.ZodTypeAny, { method: string; jsonrpc: "2.0"; params?: z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }, { method: string; jsonrpc: "2.0"; params?: z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }>; type JSONRPCNotification = z.infer<typeof JSONRPCNotificationSchema>; declare const JSONRPCMessageSchema: z.ZodUnion<[z.ZodObject<z.objectUtil.extendShape<{ jsonrpc: z.ZodLiteral<"2.0">; id: z.ZodUnion<[z.ZodString, z.ZodNumber]>; }, { method: z.ZodString; params: z.ZodOptional<z.ZodObject<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">>>; }>, "strict", z.ZodTypeAny, { id: string | number; method: string; jsonrpc: "2.0"; params?: z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }, { id: string | number; method: string; jsonrpc: "2.0"; params?: z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }>, z.ZodObject<z.objectUtil.extendShape<{ jsonrpc: z.ZodLiteral<"2.0">; }, { method: z.ZodString; params: z.ZodOptional<z.ZodObject<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">>>; }>, "strict", z.ZodTypeAny, { method: string; jsonrpc: "2.0"; params?: z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }, { method: string; jsonrpc: "2.0"; params?: z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough"> | undefined; }>, z.ZodObject<{ jsonrpc: z.ZodLiteral<"2.0">; id: z.ZodUnion<[z.ZodString, z.ZodNumber]>; result: z.ZodObject<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, z.ZodTypeAny, "passthrough">>; }, "strict", z.ZodTypeAny, { result: { _meta?: z.objectOutputType<{}, z.ZodTypeAny, "passthrough"> | undefined; } & { [k: string]: unknown; }; id: string | number; jsonrpc: "2.0"; }, { result: { _meta?: z.objectInputType<{}, z.ZodTypeAny, "passthrough"> | undefined; } & { [k: string]: unknown; }; id: string | number; jsonrpc: "2.0"; }>, z.ZodObject<{ jsonrpc: z.ZodLiteral<"2.0">; id: z.ZodUnion<[z.ZodString, z.ZodNumber]>; error: z.ZodObject<{ code: z.ZodNumber; message: z.ZodString; data: z.ZodOptional<z.ZodUnknown>; }, "strip", z.ZodTypeAny, { code: number; message: string; data?: unknown; }, { code: number; message: string; data?: unknown; }>; }, "strict", z.ZodTypeAny, { error: { code: number; message: string; data?: unknown; }; id: string | number; jsonrpc: "2.0"; }, { error: { code: number; message: string; data?: unknown; }; id: string | number; jsonrpc: "2.0"; }>]>; type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>; /** * Transport interface for MCP (Model Context Protocol) communication. * Maps to the `Transport` interface in the MCP spec. */ interface MCPTransport { /** * Initialize and start the transport */ start(): Promise<void>; /** * Send a JSON-RPC message through the transport * @param message The JSON-RPC message to send */ send(message: JSONRPCMessage): Promise<void>; /** * Clean up and close the transport */ close(): Promise<void>; /** * Event handler for transport closure */ onclose?: () => void; /** * Event handler for transport errors */ onerror?: (error: Error) => void; /** * Event handler for received messages */ onmessage?: (message: JSONRPCMessage) => void; } type MCPTransportConfig = { type: 'sse'; /** * The URL of the MCP server. */ url: string; /** * Additional HTTP headers to be sent with requests. */ headers?: Record<string, string>; }; type ToolSchemas = Record<string, { parameters: ToolParameters; }> | 'automatic' | undefined; type McpToolSet<TOOL_SCHEMAS extends ToolSchemas = 'automatic'> = TOOL_SCHEMAS extends Record<string, { parameters: ToolParameters; }> ? { [K in keyof TOOL_SCHEMAS]: Tool<TOOL_SCHEMAS[K]['parameters'], CallToolResult> & { execute: (args: inferParameters<TOOL_SCHEMAS[K]['parameters']>, options: ToolExecutionOptions) => PromiseLike<CallToolResult>; }; } : { [k: string]: Tool<z.ZodUnknown, CallToolResult> & { execute: (args: unknown, options: ToolExecutionOptions) => PromiseLike<CallToolResult>; }; }; declare const CallToolResultSchema: z.ZodUnion<[z.ZodObject<z.objectUtil.extendShape<{ _meta: z.ZodOptional<z.ZodObject<{}, "passthrough", z.ZodTypeAny, z.objectOutputType<{}, z.ZodTypeAny, "passthrough">, z.objectInputType<{}, z.ZodTypeAny, "passthrough">>>; }, { content: z.ZodArray<z.ZodUnion<[z.ZodObject<{ type: z.ZodLiteral<"text">; text: z.ZodString; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ type: z.ZodLiteral<"text">; text: z.ZodString; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ type: z.ZodLiteral<"text">; text: z.ZodString; }, z.ZodTypeAny, "passthrough">>, z.ZodObject<{ type: z.ZodLiteral<"image">; data: z.ZodString; mimeType: z.ZodString; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ type: z.ZodLiteral<"image">; data: z.ZodString; mimeType: z.ZodString; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ type: z.ZodLiteral<"image">; data: z.ZodString; mimeType: z.ZodString; }, z.ZodTypeAny, "passthrough">>, z.ZodObject<{ type: z.ZodLiteral<"resource">; resource: z.ZodUnion<[z.ZodObject<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { text: z.ZodString; }>, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { text: z.ZodString; }>, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { text: z.ZodString; }>, z.ZodTypeAny, "passthrough">>, z.ZodObject<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { blob: z.ZodString; }>, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { blob: z.ZodString; }>, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { blob: z.ZodString; }>, z.ZodTypeAny, "passthrough">>]>; }, "passthrough", z.ZodTypeAny, z.objectOutputType<{ type: z.ZodLiteral<"resource">; resource: z.ZodUnion<[z.ZodObject<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { text: z.ZodString; }>, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { text: z.ZodString; }>, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { text: z.ZodString; }>, z.ZodTypeAny, "passthrough">>, z.ZodObject<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { blob: z.ZodString; }>, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { blob: z.ZodString; }>, z.ZodTypeAny, "passthrough">, z.objectInputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { blob: z.ZodString; }>, z.ZodTypeAny, "passthrough">>]>; }, z.ZodTypeAny, "passthrough">, z.objectInputType<{ type: z.ZodLiteral<"resource">; resource: z.ZodUnion<[z.ZodObject<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { text: z.ZodString; }>, "passthrough", z.ZodTypeAny, z.objectOutputType<z.objectUtil.extendShape<{ /** * The URI of this resource. */ uri: z.ZodString; /** * The MIME type of this resource, if known. */ mimeType: z.ZodOptional<z.ZodString>; }, { tex