@copilotkitnext/agent 1.54.1-next.4 → 1.54.1-next.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/index.cjs +7 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +25 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
- package/src/__tests__/mcp-clients.test.ts +260 -0
- package/src/index.ts +36 -0
package/CHANGELOG.md
CHANGED
package/dist/index.cjs
CHANGED
|
@@ -352,6 +352,13 @@ This is state from the application that you can edit by calling AGUISendStateSna
|
|
|
352
352
|
}
|
|
353
353
|
})
|
|
354
354
|
};
|
|
355
|
+
if (this.config.mcpClients && this.config.mcpClients.length > 0) for (const client of this.config.mcpClients) {
|
|
356
|
+
const mcpTools = await client.tools();
|
|
357
|
+
streamTextParams.tools = {
|
|
358
|
+
...streamTextParams.tools,
|
|
359
|
+
...mcpTools
|
|
360
|
+
};
|
|
361
|
+
}
|
|
355
362
|
if (this.config.mcpServers && this.config.mcpServers.length > 0) for (const serverConfig of this.config.mcpServers) {
|
|
356
363
|
let transport;
|
|
357
364
|
if (serverConfig.type === "http") transport = new _modelcontextprotocol_sdk_client_streamableHttp_js.StreamableHTTPClientTransport(new URL(serverConfig.url), serverConfig.options);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["z","AbstractAgent","Observable","EventType","StreamableHTTPClientTransport","SSEClientTransport"],"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n ReasoningEndEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningMessageStartEvent,\n ReasoningStartEvent,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n SystemModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { createVertex } from \"@ai-sdk/google-vertex\";\nimport { randomUUID } from \"crypto\";\nimport { safeParseToolArgs } from \"@copilotkitnext/shared\";\nimport { z } from \"zod\";\nimport type {\n StandardSchemaV1,\n InferSchemaOutput,\n} from \"@copilotkitnext/shared\";\nimport { schemaToJsonSchema } from \"@copilotkitnext/shared\";\nimport { jsonSchema as aiJsonSchema } from \"ai\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\"\n | \"providerOptions\";\n\n/**\n * Supported model identifiers for BuiltInAgent\n */\nexport type BuiltInAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @param apiKey - Optional API key to use instead of environment variables\n * @returns LanguageModel instance\n */\nexport function resolveModel(\n spec: ModelSpecifier,\n apiKey?: string,\n): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n // Use provided apiKey, or fall back to environment variable\n const openai = createOpenAI({\n apiKey: apiKey || process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n // Use provided apiKey, or fall back to environment variable\n const anthropic = createAnthropic({\n apiKey: apiKey || process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n // Use provided apiKey, or fall back to environment variable\n const google = createGoogleGenerativeAI({\n apiKey: apiKey || process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n case \"vertex\": {\n const vertex = createVertex();\n return vertex(model);\n }\n\n default:\n throw new Error(\n `Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`,\n );\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<\n TParameters extends StandardSchemaV1 = StandardSchemaV1,\n> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BuiltInAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends StandardSchemaV1>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(\n content?: AGUIUserMessage[\"content\"],\n): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Options for converting AG-UI messages to Vercel AI SDK format\n */\nexport interface MessageConversionOptions {\n forwardSystemMessages?: boolean;\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: safeParseToolArgs(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n const schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n const schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(schema).length === 0) return true;\n return (\n typeof schema.type === \"string\" &&\n [\"object\", \"string\", \"number\", \"integer\", \"boolean\", \"array\"].includes(\n schema.type,\n )\n );\n}\n\nexport function convertToolsToVercelAITools(\n tools: RunAgentInput[\"tools\"],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.\n */\nfunction isZodSchema(schema: StandardSchemaV1): boolean {\n return schema[\"~standard\"]?.vendor === \"zod\";\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet.\n *\n * For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).\n * For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps\n * with the AI SDK's jsonSchema() helper.\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: ToolDefinition[],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (isZodSchema(tool.parameters)) {\n // Zod schemas can be passed directly to AI SDK (satisfies FlexibleSchema)\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters as any,\n execute: tool.execute,\n });\n } else {\n // Non-Zod: convert to JSON Schema and wrap with AI SDK's jsonSchema()\n const jsonSchemaObj = schemaToJsonSchema(tool.parameters);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: aiJsonSchema(jsonSchemaObj),\n execute: tool.execute,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Configuration for BuiltInAgent\n */\nexport interface BuiltInAgentConfiguration {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * API key for the model provider (OpenAI, Anthropic, Google)\n * If not provided, falls back to environment variables:\n * - OPENAI_API_KEY for OpenAI models\n * - ANTHROPIC_API_KEY for Anthropic models\n * - GOOGLE_API_KEY for Google models\n */\n apiKey?: string;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n /**\n * Forward system-role messages from input to the LLM.\n * Default: false\n */\n forwardSystemMessages?: boolean;\n /**\n * Forward developer-role messages from input to the LLM (as system messages).\n * Default: false\n */\n forwardDeveloperMessages?: boolean;\n /**\n * Provider-specific options passed to the model (e.g., OpenAI reasoningEffort).\n * Example: `{ openai: { reasoningEffort: \"high\" } }`\n */\n providerOptions?: Record<string, any>;\n}\n\nexport class BuiltInAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BuiltInAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model, passing API key if provided\n const model = resolveModel(this.config.model, this.config.apiKey);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(\n typeof input.state === \"object\" &&\n Object.keys(input.state).length === 0\n );\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages, {\n forwardSystemMessages: this.config.forwardSystemMessages,\n forwardDeveloperMessages: this.config.forwardDeveloperMessages,\n });\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(\n this.config.tools,\n );\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps\n ? stepCountIs(this.config.maxSteps)\n : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n providerOptions: this.config.providerOptions,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (\n typeof props.model === \"string\" ||\n typeof props.model === \"object\"\n ) {\n // Accept any string or LanguageModel instance for model override\n // Use the configured API key when resolving overridden models\n streamTextParams.model = resolveModel(\n props.model as string | LanguageModel,\n this.config.apiKey,\n );\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<\n Record<string, unknown>\n >;\n }\n }\n if (\n typeof props.maxOutputTokens === \"number\" &&\n this.canOverride(\"maxOutputTokens\")\n ) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (\n typeof props.temperature === \"number\" &&\n this.canOverride(\"temperature\")\n ) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (\n typeof props.presencePenalty === \"number\" &&\n this.canOverride(\"presencePenalty\")\n ) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (\n typeof props.frequencyPenalty === \"number\" &&\n this.canOverride(\"frequencyPenalty\")\n ) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (\n Array.isArray(props.stopSequences) &&\n this.canOverride(\"stopSequences\")\n ) {\n // Validate all elements are strings\n if (\n props.stopSequences.every(\n (item): item is string => typeof item === \"string\",\n )\n ) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (\n typeof props.maxRetries === \"number\" &&\n this.canOverride(\"maxRetries\")\n ) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n if (\n props.providerOptions !== undefined &&\n this.canOverride(\"providerOptions\")\n ) {\n if (\n typeof props.providerOptions === \"object\" &&\n props.providerOptions !== null\n ) {\n streamTextParams.providerOptions = props.providerOptions as Record<\n string,\n any\n >;\n }\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description:\n \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description:\n \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z\n .enum([\"add\", \"replace\", \"remove\"])\n .describe(\"The operation to perform\"),\n path: z\n .string()\n .describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(\n url,\n serverConfig.options,\n );\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(\n new URL(serverConfig.url),\n serverConfig.headers,\n );\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({\n ...streamTextParams,\n abortSignal: abortController.signal,\n });\n\n let messageId = randomUUID();\n let reasoningMessageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"abort\": {\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n case \"reasoning-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n if (providedId && providedId !== \"0\") {\n reasoningMessageId = providedId as typeof reasoningMessageId;\n }\n const reasoningStartEvent: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningStartEvent);\n const reasoningMessageStart: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n subscriber.next(reasoningMessageStart);\n break;\n }\n case \"reasoning-delta\": {\n const reasoningDeltaEvent: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta:\n (\"text\" in part ? part.text : (part as any).delta) ?? \"\",\n };\n subscriber.next(reasoningDeltaEvent);\n break;\n }\n case \"reasoning-end\": {\n const reasoningMessageEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningMessageEnd);\n const reasoningEndEvent: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningEndEvent);\n break;\n }\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n messageId =\n providedId && providedId !== \"0\"\n ? (providedId as typeof messageId)\n : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (\n !state.hasArgsDelta &&\n \"input\" in part &&\n part.input !== undefined\n ) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (\n toolName === \"AGUISendStateSnapshot\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (\n toolName === \"AGUISendStateDelta\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\": {\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n const cloned = new BuiltInAgent(this.config);\n // Copy middlewares from parent class\n // @ts-expect-error - accessing protected property from parent\n cloned.middlewares = [...this.middlewares];\n return cloned;\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n\n/**\n * @deprecated Use BuiltInAgent instead\n */\nexport class BasicAgent extends BuiltInAgent {\n constructor(config: BuiltInAgentConfiguration) {\n super(config);\n console.warn(\"BasicAgent is deprecated, use BuiltInAgent instead\");\n }\n}\n\nexport type BasicAgentConfiguration = BuiltInAgentConfiguration;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgKA,SAAgB,aACd,MACA,QACe;AAEf,KAAI,OAAO,SAAS,SAClB,QAAO;CAKT,MAAM,QADa,KAAK,QAAQ,KAAK,IAAI,CAAC,MAAM,CACvB,MAAM,IAAI;CACnC,MAAM,cAAc,MAAM;CAC1B,MAAM,OAAO,MAAM,MAAM,EAAE;AAE3B,KAAI,CAAC,YACH,OAAM,IAAI,MACR,yBAAyB,KAAK,mFAC/B;CAGH,MAAM,WAAW,YAAY,aAAa;CAC1C,MAAM,QAAQ,KAAK,KAAK,IAAI,CAAC,MAAM;AAEnC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,yBAAyB,KAAK,mFAC/B;AAGH,SAAQ,UAAR;EACE,KAAK,SAOH,yCAJ4B,EAC1B,QAAQ,UAAU,QAAQ,IAAI,gBAC/B,CAAC,CAEY,MAAM;EAGtB,KAAK,YAOH,+CAJkC,EAChC,QAAQ,UAAU,QAAQ,IAAI,mBAC/B,CAAC,CAEe,MAAM;EAGzB,KAAK;EACL,KAAK;EACL,KAAK,gBAOH,qDAJwC,EACtC,QAAQ,UAAU,QAAQ,IAAI,gBAC/B,CAAC,CAEY,MAAM;EAGtB,KAAK,SAEH,iDAD6B,CACf,MAAM;EAGtB,QACE,OAAM,IAAI,MACR,qBAAqB,SAAS,QAAQ,KAAK,mDAC5C;;;;;;;;;;;AAwBP,SAAgB,WAAiD,QAKjC;AAC9B,QAAO;EACL,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,SAAS,OAAO;EACjB;;AAKH,SAAS,0BACP,SACQ;AACR,KAAI,CAAC,QACH,QAAO;AAGT,KAAI,OAAO,YAAY,SACrB,QAAO;AAGT,QAAO,QACJ,KAAK,SAA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;AACvB,WAAM,QAAQ,IAAI,WAAW,KAAK,WAAW,OAAO,OAAO,CAAC,CAAC;;OAE7D;AAGJ,gBAAa;AAEX,YAAQ,IAAI,WAAW,KAAK,WAAW,OAAO,OAAO,CAAC,CAAC,CAAC,YAAY,GAElE;;IAEJ;;CAGJ,QAAQ;EACN,MAAM,SAAS,IAAI,aAAa,KAAK,OAAO;AAG5C,SAAO,cAAc,CAAC,GAAG,KAAK,YAAY;AAC1C,SAAO;;CAGT,WAAiB;AACf,OAAK,iBAAiB,OAAO;;;;;;AAOjC,IAAa,aAAb,cAAgC,aAAa;CAC3C,YAAY,QAAmC;AAC7C,QAAM,OAAO;AACb,UAAQ,KAAK,qDAAqD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["z","AbstractAgent","Observable","EventType","StreamableHTTPClientTransport","SSEClientTransport"],"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n ReasoningEndEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningMessageStartEvent,\n ReasoningStartEvent,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n SystemModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { createVertex } from \"@ai-sdk/google-vertex\";\nimport { randomUUID } from \"crypto\";\nimport { safeParseToolArgs } from \"@copilotkitnext/shared\";\nimport { z } from \"zod\";\nimport type {\n StandardSchemaV1,\n InferSchemaOutput,\n} from \"@copilotkitnext/shared\";\nimport { schemaToJsonSchema } from \"@copilotkitnext/shared\";\nimport { jsonSchema as aiJsonSchema } from \"ai\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\"\n | \"providerOptions\";\n\n/**\n * Supported model identifiers for BuiltInAgent\n */\nexport type BuiltInAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * A user-managed MCP client that provides tools to the agent.\n * The user is responsible for creating, configuring, and closing the client.\n * Compatible with the return type of @ai-sdk/mcp's createMCPClient().\n *\n * Unlike mcpServers, the agent does NOT create or close these clients.\n * This allows persistent connections, custom auth, and tool caching.\n */\nexport interface MCPClientProvider {\n /** Return tools to be merged into the agent's tool set. */\n tools(): Promise<ToolSet>;\n}\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @param apiKey - Optional API key to use instead of environment variables\n * @returns LanguageModel instance\n */\nexport function resolveModel(\n spec: ModelSpecifier,\n apiKey?: string,\n): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n // Use provided apiKey, or fall back to environment variable\n const openai = createOpenAI({\n apiKey: apiKey || process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n // Use provided apiKey, or fall back to environment variable\n const anthropic = createAnthropic({\n apiKey: apiKey || process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n // Use provided apiKey, or fall back to environment variable\n const google = createGoogleGenerativeAI({\n apiKey: apiKey || process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n case \"vertex\": {\n const vertex = createVertex();\n return vertex(model);\n }\n\n default:\n throw new Error(\n `Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`,\n );\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<\n TParameters extends StandardSchemaV1 = StandardSchemaV1,\n> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BuiltInAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends StandardSchemaV1>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(\n content?: AGUIUserMessage[\"content\"],\n): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Options for converting AG-UI messages to Vercel AI SDK format\n */\nexport interface MessageConversionOptions {\n forwardSystemMessages?: boolean;\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: safeParseToolArgs(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n const schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n const schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(schema).length === 0) return true;\n return (\n typeof schema.type === \"string\" &&\n [\"object\", \"string\", \"number\", \"integer\", \"boolean\", \"array\"].includes(\n schema.type,\n )\n );\n}\n\nexport function convertToolsToVercelAITools(\n tools: RunAgentInput[\"tools\"],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.\n */\nfunction isZodSchema(schema: StandardSchemaV1): boolean {\n return schema[\"~standard\"]?.vendor === \"zod\";\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet.\n *\n * For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).\n * For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps\n * with the AI SDK's jsonSchema() helper.\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: ToolDefinition[],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (isZodSchema(tool.parameters)) {\n // Zod schemas can be passed directly to AI SDK (satisfies FlexibleSchema)\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters as any,\n execute: tool.execute,\n });\n } else {\n // Non-Zod: convert to JSON Schema and wrap with AI SDK's jsonSchema()\n const jsonSchemaObj = schemaToJsonSchema(tool.parameters);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: aiJsonSchema(jsonSchemaObj),\n execute: tool.execute,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Configuration for BuiltInAgent\n */\nexport interface BuiltInAgentConfiguration {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * API key for the model provider (OpenAI, Anthropic, Google)\n * If not provided, falls back to environment variables:\n * - OPENAI_API_KEY for OpenAI models\n * - ANTHROPIC_API_KEY for Anthropic models\n * - GOOGLE_API_KEY for Google models\n */\n apiKey?: string;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional list of user-managed MCP clients.\n * Unlike mcpServers, the agent does NOT create or close these clients.\n * The user controls the lifecycle, persistence, auth, and caching.\n *\n * Compatible with @ai-sdk/mcp's createMCPClient() return type:\n * ```typescript\n * const client = await createMCPClient({ transport });\n * const agent = new BuiltInAgent({ model: \"...\", mcpClients: [client] });\n * ```\n */\n mcpClients?: MCPClientProvider[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n /**\n * Forward system-role messages from input to the LLM.\n * Default: false\n */\n forwardSystemMessages?: boolean;\n /**\n * Forward developer-role messages from input to the LLM (as system messages).\n * Default: false\n */\n forwardDeveloperMessages?: boolean;\n /**\n * Provider-specific options passed to the model (e.g., OpenAI reasoningEffort).\n * Example: `{ openai: { reasoningEffort: \"high\" } }`\n */\n providerOptions?: Record<string, any>;\n}\n\nexport class BuiltInAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BuiltInAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model, passing API key if provided\n const model = resolveModel(this.config.model, this.config.apiKey);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(\n typeof input.state === \"object\" &&\n Object.keys(input.state).length === 0\n );\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages, {\n forwardSystemMessages: this.config.forwardSystemMessages,\n forwardDeveloperMessages: this.config.forwardDeveloperMessages,\n });\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(\n this.config.tools,\n );\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps\n ? stepCountIs(this.config.maxSteps)\n : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n providerOptions: this.config.providerOptions,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (\n typeof props.model === \"string\" ||\n typeof props.model === \"object\"\n ) {\n // Accept any string or LanguageModel instance for model override\n // Use the configured API key when resolving overridden models\n streamTextParams.model = resolveModel(\n props.model as string | LanguageModel,\n this.config.apiKey,\n );\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<\n Record<string, unknown>\n >;\n }\n }\n if (\n typeof props.maxOutputTokens === \"number\" &&\n this.canOverride(\"maxOutputTokens\")\n ) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (\n typeof props.temperature === \"number\" &&\n this.canOverride(\"temperature\")\n ) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (\n typeof props.presencePenalty === \"number\" &&\n this.canOverride(\"presencePenalty\")\n ) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (\n typeof props.frequencyPenalty === \"number\" &&\n this.canOverride(\"frequencyPenalty\")\n ) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (\n Array.isArray(props.stopSequences) &&\n this.canOverride(\"stopSequences\")\n ) {\n // Validate all elements are strings\n if (\n props.stopSequences.every(\n (item): item is string => typeof item === \"string\",\n )\n ) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (\n typeof props.maxRetries === \"number\" &&\n this.canOverride(\"maxRetries\")\n ) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n if (\n props.providerOptions !== undefined &&\n this.canOverride(\"providerOptions\")\n ) {\n if (\n typeof props.providerOptions === \"object\" &&\n props.providerOptions !== null\n ) {\n streamTextParams.providerOptions = props.providerOptions as Record<\n string,\n any\n >;\n }\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description:\n \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description:\n \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z\n .enum([\"add\", \"replace\", \"remove\"])\n .describe(\"The operation to perform\"),\n path: z\n .string()\n .describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Merge tools from user-managed MCP clients (user controls lifecycle)\n if (this.config.mcpClients && this.config.mcpClients.length > 0) {\n for (const client of this.config.mcpClients) {\n const mcpTools = await client.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(\n url,\n serverConfig.options,\n );\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(\n new URL(serverConfig.url),\n serverConfig.headers,\n );\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({\n ...streamTextParams,\n abortSignal: abortController.signal,\n });\n\n let messageId = randomUUID();\n let reasoningMessageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"abort\": {\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n case \"reasoning-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n if (providedId && providedId !== \"0\") {\n reasoningMessageId = providedId as typeof reasoningMessageId;\n }\n const reasoningStartEvent: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningStartEvent);\n const reasoningMessageStart: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n subscriber.next(reasoningMessageStart);\n break;\n }\n case \"reasoning-delta\": {\n const reasoningDeltaEvent: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta:\n (\"text\" in part ? part.text : (part as any).delta) ?? \"\",\n };\n subscriber.next(reasoningDeltaEvent);\n break;\n }\n case \"reasoning-end\": {\n const reasoningMessageEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningMessageEnd);\n const reasoningEndEvent: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningEndEvent);\n break;\n }\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n messageId =\n providedId && providedId !== \"0\"\n ? (providedId as typeof messageId)\n : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (\n !state.hasArgsDelta &&\n \"input\" in part &&\n part.input !== undefined\n ) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (\n toolName === \"AGUISendStateSnapshot\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (\n toolName === \"AGUISendStateDelta\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\": {\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n const cloned = new BuiltInAgent(this.config);\n // Copy middlewares from parent class\n // @ts-expect-error - accessing protected property from parent\n cloned.middlewares = [...this.middlewares];\n return cloned;\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n\n/**\n * @deprecated Use BuiltInAgent instead\n */\nexport class BasicAgent extends BuiltInAgent {\n constructor(config: BuiltInAgentConfiguration) {\n super(config);\n console.warn(\"BasicAgent is deprecated, use BuiltInAgent instead\");\n }\n}\n\nexport type BasicAgentConfiguration = BuiltInAgentConfiguration;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA6KA,SAAgB,aACd,MACA,QACe;AAEf,KAAI,OAAO,SAAS,SAClB,QAAO;CAKT,MAAM,QADa,KAAK,QAAQ,KAAK,IAAI,CAAC,MAAM,CACvB,MAAM,IAAI;CACnC,MAAM,cAAc,MAAM;CAC1B,MAAM,OAAO,MAAM,MAAM,EAAE;AAE3B,KAAI,CAAC,YACH,OAAM,IAAI,MACR,yBAAyB,KAAK,mFAC/B;CAGH,MAAM,WAAW,YAAY,aAAa;CAC1C,MAAM,QAAQ,KAAK,KAAK,IAAI,CAAC,MAAM;AAEnC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,yBAAyB,KAAK,mFAC/B;AAGH,SAAQ,UAAR;EACE,KAAK,SAOH,yCAJ4B,EAC1B,QAAQ,UAAU,QAAQ,IAAI,gBAC/B,CAAC,CAEY,MAAM;EAGtB,KAAK,YAOH,+CAJkC,EAChC,QAAQ,UAAU,QAAQ,IAAI,mBAC/B,CAAC,CAEe,MAAM;EAGzB,KAAK;EACL,KAAK;EACL,KAAK,gBAOH,qDAJwC,EACtC,QAAQ,UAAU,QAAQ,IAAI,gBAC/B,CAAC,CAEY,MAAM;EAGtB,KAAK,SAEH,iDAD6B,CACf,MAAM;EAGtB,QACE,OAAM,IAAI,MACR,qBAAqB,SAAS,QAAQ,KAAK,mDAC5C;;;;;;;;;;;AAwBP,SAAgB,WAAiD,QAKjC;AAC9B,QAAO;EACL,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,SAAS,OAAO;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ChB,UAAU,MAAM;QAChB,OAAO,MAAM;QACd;AACD,kBAAW,KAAK,cAAc;;AAGhC,6BAAuB;AACvB,iBAAW,UAAU;;aAEhB,OAAO;AACd,SAAI,gBAAgB,OAAO,QACzB,YAAW,UAAU;UAChB;MACL,MAAM,gBAA+B;OACnC,MAAMA,wBAAU;OAChB,SAAS,QAAQ;OAClB;AACD,iBAAW,KAAK,cAAc;AAC9B,6BAAuB;AACvB,iBAAW,MAAM,MAAM;;cAEjB;AACR,UAAK,kBAAkB;AACvB,WAAM,QAAQ,IAAI,WAAW,KAAK,WAAW,OAAO,OAAO,CAAC,CAAC;;OAE7D;AAGJ,gBAAa;AAEX,YAAQ,IAAI,WAAW,KAAK,WAAW,OAAO,OAAO,CAAC,CAAC,CAAC,YAAY,GAElE;;IAEJ;;CAGJ,QAAQ;EACN,MAAM,SAAS,IAAI,aAAa,KAAK,OAAO;AAG5C,SAAO,cAAc,CAAC,GAAG,KAAK,YAAY;AAC1C,SAAO;;CAGT,WAAiB;AACf,OAAK,iBAAiB,OAAO;;;;;;AAOjC,IAAa,aAAb,cAAgC,aAAa;CAC3C,YAAY,QAAmC;AAC7C,QAAM,OAAO;AACb,UAAQ,KAAK,qDAAqD"}
|
package/dist/index.d.cts
CHANGED
|
@@ -57,6 +57,18 @@ interface MCPClientConfigSSE {
|
|
|
57
57
|
* MCP Client configuration
|
|
58
58
|
*/
|
|
59
59
|
type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;
|
|
60
|
+
/**
|
|
61
|
+
* A user-managed MCP client that provides tools to the agent.
|
|
62
|
+
* The user is responsible for creating, configuring, and closing the client.
|
|
63
|
+
* Compatible with the return type of @ai-sdk/mcp's createMCPClient().
|
|
64
|
+
*
|
|
65
|
+
* Unlike mcpServers, the agent does NOT create or close these clients.
|
|
66
|
+
* This allows persistent connections, custom auth, and tool caching.
|
|
67
|
+
*/
|
|
68
|
+
interface MCPClientProvider {
|
|
69
|
+
/** Return tools to be merged into the agent's tool set. */
|
|
70
|
+
tools(): Promise<ToolSet>;
|
|
71
|
+
}
|
|
60
72
|
/**
|
|
61
73
|
* Resolves a model specifier to a LanguageModel instance
|
|
62
74
|
* @param spec - Model string (e.g., "openai/gpt-4o") or LanguageModel instance
|
|
@@ -194,6 +206,18 @@ interface BuiltInAgentConfiguration {
|
|
|
194
206
|
* Optional list of MCP server configurations
|
|
195
207
|
*/
|
|
196
208
|
mcpServers?: MCPClientConfig[];
|
|
209
|
+
/**
|
|
210
|
+
* Optional list of user-managed MCP clients.
|
|
211
|
+
* Unlike mcpServers, the agent does NOT create or close these clients.
|
|
212
|
+
* The user controls the lifecycle, persistence, auth, and caching.
|
|
213
|
+
*
|
|
214
|
+
* Compatible with @ai-sdk/mcp's createMCPClient() return type:
|
|
215
|
+
* ```typescript
|
|
216
|
+
* const client = await createMCPClient({ transport });
|
|
217
|
+
* const agent = new BuiltInAgent({ model: "...", mcpClients: [client] });
|
|
218
|
+
* ```
|
|
219
|
+
*/
|
|
220
|
+
mcpClients?: MCPClientProvider[];
|
|
197
221
|
/**
|
|
198
222
|
* Optional tools available to the agent
|
|
199
223
|
*/
|
|
@@ -234,5 +258,5 @@ declare class BasicAgent extends BuiltInAgent {
|
|
|
234
258
|
}
|
|
235
259
|
type BasicAgentConfiguration = BuiltInAgentConfiguration;
|
|
236
260
|
//#endregion
|
|
237
|
-
export { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentConfiguration, BuiltInAgentModel, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
|
|
261
|
+
export { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentConfiguration, BuiltInAgentModel, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
|
|
238
262
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;AA+DA;;KAAY,mBAAA;;;AAkBZ;KAAY,iBAAA;;;;KA8BA,cAAA,YAA0B,aAAA;;;;UAKrB,mBAAA;EAAA;;;EAIf,IAAA;EAAA;;;EAIA,GAAA;EAI8C;;AAMhD;EANE,OAAA,GAAU,oCAAA;AAAA;;;;UAMK,kBAAA;EAYL;;;EARV,IAAA;EAcyB;;;EAVzB,GAAA;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;AA+DA;;KAAY,mBAAA;;;AAkBZ;KAAY,iBAAA;;;;KA8BA,cAAA,YAA0B,aAAA;;;;UAKrB,mBAAA;EAAA;;;EAIf,IAAA;EAAA;;;EAIA,GAAA;EAI8C;;AAMhD;EANE,OAAA,GAAU,oCAAA;AAAA;;;;UAMK,kBAAA;EAYL;;;EARV,IAAA;EAcyB;;;EAVzB,GAAA;EAoBe;;;EAhBf,OAAA,GAAU,MAAA;AAAA;;;;KAMA,eAAA,GAAkB,mBAAA,GAAsB,kBAAA;AAqBpD;;;;;;;;AAAA,UAXiB,iBAAA;EAcD;EAZd,KAAA,IAAS,OAAA,CAAQ,OAAA;AAAA;;;;;;;iBASH,YAAA,CACd,IAAA,EAAM,cAAA,EACN,MAAA,YACC,aAAA;;;;UA2Ec,cAAA,qBACK,gBAAA,GAAmB,gBAAA;EAEvC,IAAA;EACA,WAAA;EACA,UAAA,EAAY,WAAA;EACZ,OAAA,GAAU,IAAA,EAAM,iBAAA,CAAkB,WAAA,MAAiB,OAAA;AAAA;;;;;;;;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Q;;;;EAUR,wBAAA;EAKwB;;AAG1B;;EAHE,eAAA,GAAkB,MAAA;AAAA;AAAA,cAGP,YAAA,SAAqB,aAAA;EAAA,QAGZ,MAAA;EAAA,QAFZ,eAAA;cAEY,MAAA,EAAQ,yBAAA;EAmnBvB;;;EA5mBL,WAAA,CAAY,QAAA,EAAU,mBAAA;EAItB,GAAA,CAAI,KAAA,EAAO,aAAA,GAAgB,UAAA,CAAW,SAAA;EAwmBtC,KAAA,CAAA,GAAK,YAAA;EAQL,QAAA,CAAA;AAAA;;;;cAQW,UAAA,SAAmB,YAAA;cAClB,MAAA,EAAQ,yBAAA;AAAA;AAAA,KAMV,uBAAA,GAA0B,yBAAA"}
|
package/dist/index.d.mts
CHANGED
|
@@ -57,6 +57,18 @@ interface MCPClientConfigSSE {
|
|
|
57
57
|
* MCP Client configuration
|
|
58
58
|
*/
|
|
59
59
|
type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;
|
|
60
|
+
/**
|
|
61
|
+
* A user-managed MCP client that provides tools to the agent.
|
|
62
|
+
* The user is responsible for creating, configuring, and closing the client.
|
|
63
|
+
* Compatible with the return type of @ai-sdk/mcp's createMCPClient().
|
|
64
|
+
*
|
|
65
|
+
* Unlike mcpServers, the agent does NOT create or close these clients.
|
|
66
|
+
* This allows persistent connections, custom auth, and tool caching.
|
|
67
|
+
*/
|
|
68
|
+
interface MCPClientProvider {
|
|
69
|
+
/** Return tools to be merged into the agent's tool set. */
|
|
70
|
+
tools(): Promise<ToolSet>;
|
|
71
|
+
}
|
|
60
72
|
/**
|
|
61
73
|
* Resolves a model specifier to a LanguageModel instance
|
|
62
74
|
* @param spec - Model string (e.g., "openai/gpt-4o") or LanguageModel instance
|
|
@@ -194,6 +206,18 @@ interface BuiltInAgentConfiguration {
|
|
|
194
206
|
* Optional list of MCP server configurations
|
|
195
207
|
*/
|
|
196
208
|
mcpServers?: MCPClientConfig[];
|
|
209
|
+
/**
|
|
210
|
+
* Optional list of user-managed MCP clients.
|
|
211
|
+
* Unlike mcpServers, the agent does NOT create or close these clients.
|
|
212
|
+
* The user controls the lifecycle, persistence, auth, and caching.
|
|
213
|
+
*
|
|
214
|
+
* Compatible with @ai-sdk/mcp's createMCPClient() return type:
|
|
215
|
+
* ```typescript
|
|
216
|
+
* const client = await createMCPClient({ transport });
|
|
217
|
+
* const agent = new BuiltInAgent({ model: "...", mcpClients: [client] });
|
|
218
|
+
* ```
|
|
219
|
+
*/
|
|
220
|
+
mcpClients?: MCPClientProvider[];
|
|
197
221
|
/**
|
|
198
222
|
* Optional tools available to the agent
|
|
199
223
|
*/
|
|
@@ -234,5 +258,5 @@ declare class BasicAgent extends BuiltInAgent {
|
|
|
234
258
|
}
|
|
235
259
|
type BasicAgentConfiguration = BuiltInAgentConfiguration;
|
|
236
260
|
//#endregion
|
|
237
|
-
export { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentConfiguration, BuiltInAgentModel, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
|
|
261
|
+
export { BasicAgent, BasicAgentConfiguration, BuiltInAgent, BuiltInAgentConfiguration, BuiltInAgentModel, MCPClientConfig, MCPClientConfigHTTP, MCPClientConfigSSE, MCPClientProvider, MessageConversionOptions, ModelSpecifier, OverridableProperty, ToolDefinition, convertJsonSchemaToZodSchema, convertMessagesToVercelAISDKMessages, convertToolDefinitionsToVercelAITools, convertToolsToVercelAITools, defineTool, resolveModel };
|
|
238
262
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;AA+DA;;KAAY,mBAAA;;;AAkBZ;KAAY,iBAAA;;;;KA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AAA;AAAA;;;;cAQW,UAAA,SAAmB,YAAA;cAClB,MAAA,EAAQ,yBAAA;AAAA;AAAA,KAMV,uBAAA,GAA0B,yBAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -351,6 +351,13 @@ This is state from the application that you can edit by calling AGUISendStateSna
|
|
|
351
351
|
}
|
|
352
352
|
})
|
|
353
353
|
};
|
|
354
|
+
if (this.config.mcpClients && this.config.mcpClients.length > 0) for (const client of this.config.mcpClients) {
|
|
355
|
+
const mcpTools = await client.tools();
|
|
356
|
+
streamTextParams.tools = {
|
|
357
|
+
...streamTextParams.tools,
|
|
358
|
+
...mcpTools
|
|
359
|
+
};
|
|
360
|
+
}
|
|
354
361
|
if (this.config.mcpServers && this.config.mcpServers.length > 0) for (const serverConfig of this.config.mcpServers) {
|
|
355
362
|
let transport;
|
|
356
363
|
if (serverConfig.type === "http") transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), serverConfig.options);
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["tool","createVercelAISDKTool","aiJsonSchema","createMCPClient"],"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n ReasoningEndEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningMessageStartEvent,\n ReasoningStartEvent,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n SystemModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { createVertex } from \"@ai-sdk/google-vertex\";\nimport { randomUUID } from \"crypto\";\nimport { safeParseToolArgs } from \"@copilotkitnext/shared\";\nimport { z } from \"zod\";\nimport type {\n StandardSchemaV1,\n InferSchemaOutput,\n} from \"@copilotkitnext/shared\";\nimport { schemaToJsonSchema } from \"@copilotkitnext/shared\";\nimport { jsonSchema as aiJsonSchema } from \"ai\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\"\n | \"providerOptions\";\n\n/**\n * Supported model identifiers for BuiltInAgent\n */\nexport type BuiltInAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @param apiKey - Optional API key to use instead of environment variables\n * @returns LanguageModel instance\n */\nexport function resolveModel(\n spec: ModelSpecifier,\n apiKey?: string,\n): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n // Use provided apiKey, or fall back to environment variable\n const openai = createOpenAI({\n apiKey: apiKey || process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n // Use provided apiKey, or fall back to environment variable\n const anthropic = createAnthropic({\n apiKey: apiKey || process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n // Use provided apiKey, or fall back to environment variable\n const google = createGoogleGenerativeAI({\n apiKey: apiKey || process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n case \"vertex\": {\n const vertex = createVertex();\n return vertex(model);\n }\n\n default:\n throw new Error(\n `Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`,\n );\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<\n TParameters extends StandardSchemaV1 = StandardSchemaV1,\n> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BuiltInAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends StandardSchemaV1>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(\n content?: AGUIUserMessage[\"content\"],\n): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Options for converting AG-UI messages to Vercel AI SDK format\n */\nexport interface MessageConversionOptions {\n forwardSystemMessages?: boolean;\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: safeParseToolArgs(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n const schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n const schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(schema).length === 0) return true;\n return (\n typeof schema.type === \"string\" &&\n [\"object\", \"string\", \"number\", \"integer\", \"boolean\", \"array\"].includes(\n schema.type,\n )\n );\n}\n\nexport function convertToolsToVercelAITools(\n tools: RunAgentInput[\"tools\"],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.\n */\nfunction isZodSchema(schema: StandardSchemaV1): boolean {\n return schema[\"~standard\"]?.vendor === \"zod\";\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet.\n *\n * For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).\n * For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps\n * with the AI SDK's jsonSchema() helper.\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: ToolDefinition[],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (isZodSchema(tool.parameters)) {\n // Zod schemas can be passed directly to AI SDK (satisfies FlexibleSchema)\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters as any,\n execute: tool.execute,\n });\n } else {\n // Non-Zod: convert to JSON Schema and wrap with AI SDK's jsonSchema()\n const jsonSchemaObj = schemaToJsonSchema(tool.parameters);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: aiJsonSchema(jsonSchemaObj),\n execute: tool.execute,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Configuration for BuiltInAgent\n */\nexport interface BuiltInAgentConfiguration {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * API key for the model provider (OpenAI, Anthropic, Google)\n * If not provided, falls back to environment variables:\n * - OPENAI_API_KEY for OpenAI models\n * - ANTHROPIC_API_KEY for Anthropic models\n * - GOOGLE_API_KEY for Google models\n */\n apiKey?: string;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n /**\n * Forward system-role messages from input to the LLM.\n * Default: false\n */\n forwardSystemMessages?: boolean;\n /**\n * Forward developer-role messages from input to the LLM (as system messages).\n * Default: false\n */\n forwardDeveloperMessages?: boolean;\n /**\n * Provider-specific options passed to the model (e.g., OpenAI reasoningEffort).\n * Example: `{ openai: { reasoningEffort: \"high\" } }`\n */\n providerOptions?: Record<string, any>;\n}\n\nexport class BuiltInAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BuiltInAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model, passing API key if provided\n const model = resolveModel(this.config.model, this.config.apiKey);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(\n typeof input.state === \"object\" &&\n Object.keys(input.state).length === 0\n );\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages, {\n forwardSystemMessages: this.config.forwardSystemMessages,\n forwardDeveloperMessages: this.config.forwardDeveloperMessages,\n });\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(\n this.config.tools,\n );\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps\n ? stepCountIs(this.config.maxSteps)\n : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n providerOptions: this.config.providerOptions,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (\n typeof props.model === \"string\" ||\n typeof props.model === \"object\"\n ) {\n // Accept any string or LanguageModel instance for model override\n // Use the configured API key when resolving overridden models\n streamTextParams.model = resolveModel(\n props.model as string | LanguageModel,\n this.config.apiKey,\n );\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<\n Record<string, unknown>\n >;\n }\n }\n if (\n typeof props.maxOutputTokens === \"number\" &&\n this.canOverride(\"maxOutputTokens\")\n ) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (\n typeof props.temperature === \"number\" &&\n this.canOverride(\"temperature\")\n ) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (\n typeof props.presencePenalty === \"number\" &&\n this.canOverride(\"presencePenalty\")\n ) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (\n typeof props.frequencyPenalty === \"number\" &&\n this.canOverride(\"frequencyPenalty\")\n ) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (\n Array.isArray(props.stopSequences) &&\n this.canOverride(\"stopSequences\")\n ) {\n // Validate all elements are strings\n if (\n props.stopSequences.every(\n (item): item is string => typeof item === \"string\",\n )\n ) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (\n typeof props.maxRetries === \"number\" &&\n this.canOverride(\"maxRetries\")\n ) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n if (\n props.providerOptions !== undefined &&\n this.canOverride(\"providerOptions\")\n ) {\n if (\n typeof props.providerOptions === \"object\" &&\n props.providerOptions !== null\n ) {\n streamTextParams.providerOptions = props.providerOptions as Record<\n string,\n any\n >;\n }\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description:\n \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description:\n \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z\n .enum([\"add\", \"replace\", \"remove\"])\n .describe(\"The operation to perform\"),\n path: z\n .string()\n .describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(\n url,\n serverConfig.options,\n );\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(\n new URL(serverConfig.url),\n serverConfig.headers,\n );\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({\n ...streamTextParams,\n abortSignal: abortController.signal,\n });\n\n let messageId = randomUUID();\n let reasoningMessageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"abort\": {\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n case \"reasoning-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n if (providedId && providedId !== \"0\") {\n reasoningMessageId = providedId as typeof reasoningMessageId;\n }\n const reasoningStartEvent: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningStartEvent);\n const reasoningMessageStart: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n subscriber.next(reasoningMessageStart);\n break;\n }\n case \"reasoning-delta\": {\n const reasoningDeltaEvent: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta:\n (\"text\" in part ? part.text : (part as any).delta) ?? \"\",\n };\n subscriber.next(reasoningDeltaEvent);\n break;\n }\n case \"reasoning-end\": {\n const reasoningMessageEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningMessageEnd);\n const reasoningEndEvent: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningEndEvent);\n break;\n }\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n messageId =\n providedId && providedId !== \"0\"\n ? (providedId as typeof messageId)\n : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (\n !state.hasArgsDelta &&\n \"input\" in part &&\n part.input !== undefined\n ) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (\n toolName === \"AGUISendStateSnapshot\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (\n toolName === \"AGUISendStateDelta\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\": {\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n const cloned = new BuiltInAgent(this.config);\n // Copy middlewares from parent class\n // @ts-expect-error - accessing protected property from parent\n cloned.middlewares = [...this.middlewares];\n return cloned;\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n\n/**\n * @deprecated Use BuiltInAgent instead\n */\nexport class BasicAgent extends BuiltInAgent {\n constructor(config: BuiltInAgentConfiguration) {\n super(config);\n console.warn(\"BasicAgent is deprecated, use BuiltInAgent instead\");\n }\n}\n\nexport type BasicAgentConfiguration = BuiltInAgentConfiguration;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgKA,SAAgB,aACd,MACA,QACe;AAEf,KAAI,OAAO,SAAS,SAClB,QAAO;CAKT,MAAM,QADa,KAAK,QAAQ,KAAK,IAAI,CAAC,MAAM,CACvB,MAAM,IAAI;CACnC,MAAM,cAAc,MAAM;CAC1B,MAA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;;CAGT,WAAiB;AACf,OAAK,iBAAiB,OAAO;;;;;;AAOjC,IAAa,aAAb,cAAgC,aAAa;CAC3C,YAAY,QAAmC;AAC7C,QAAM,OAAO;AACb,UAAQ,KAAK,qDAAqD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["tool","createVercelAISDKTool","aiJsonSchema","createMCPClient"],"sources":["../src/index.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n RunAgentInput,\n EventType,\n Message,\n ReasoningEndEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningMessageStartEvent,\n ReasoningStartEvent,\n RunFinishedEvent,\n RunStartedEvent,\n TextMessageChunkEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ToolCallResultEvent,\n RunErrorEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/client\";\nimport {\n streamText,\n LanguageModel,\n ModelMessage,\n AssistantModelMessage,\n UserModelMessage,\n ToolModelMessage,\n SystemModelMessage,\n ToolCallPart,\n ToolResultPart,\n TextPart,\n tool as createVercelAISDKTool,\n ToolChoice,\n ToolSet,\n stepCountIs,\n} from \"ai\";\nimport { experimental_createMCPClient as createMCPClient } from \"@ai-sdk/mcp\";\nimport { Observable } from \"rxjs\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { createGoogleGenerativeAI } from \"@ai-sdk/google\";\nimport { createVertex } from \"@ai-sdk/google-vertex\";\nimport { randomUUID } from \"crypto\";\nimport { safeParseToolArgs } from \"@copilotkitnext/shared\";\nimport { z } from \"zod\";\nimport type {\n StandardSchemaV1,\n InferSchemaOutput,\n} from \"@copilotkitnext/shared\";\nimport { schemaToJsonSchema } from \"@copilotkitnext/shared\";\nimport { jsonSchema as aiJsonSchema } from \"ai\";\nimport {\n StreamableHTTPClientTransport,\n StreamableHTTPClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\n/**\n * Properties that can be overridden by forwardedProps\n * These match the exact parameter names in streamText\n */\nexport type OverridableProperty =\n | \"model\"\n | \"toolChoice\"\n | \"maxOutputTokens\"\n | \"temperature\"\n | \"topP\"\n | \"topK\"\n | \"presencePenalty\"\n | \"frequencyPenalty\"\n | \"stopSequences\"\n | \"seed\"\n | \"maxRetries\"\n | \"prompt\"\n | \"providerOptions\";\n\n/**\n * Supported model identifiers for BuiltInAgent\n */\nexport type BuiltInAgentModel =\n // OpenAI models\n | \"openai/gpt-5\"\n | \"openai/gpt-5-mini\"\n | \"openai/gpt-4.1\"\n | \"openai/gpt-4.1-mini\"\n | \"openai/gpt-4.1-nano\"\n | \"openai/gpt-4o\"\n | \"openai/gpt-4o-mini\"\n // OpenAI reasoning series\n | \"openai/o3\"\n | \"openai/o3-mini\"\n | \"openai/o4-mini\"\n // Anthropic (Claude) models\n | \"anthropic/claude-sonnet-4.5\"\n | \"anthropic/claude-sonnet-4\"\n | \"anthropic/claude-3.7-sonnet\"\n | \"anthropic/claude-opus-4.1\"\n | \"anthropic/claude-opus-4\"\n | \"anthropic/claude-3.5-haiku\"\n // Google (Gemini) models\n | \"google/gemini-2.5-pro\"\n | \"google/gemini-2.5-flash\"\n | \"google/gemini-2.5-flash-lite\"\n // Allow any LanguageModel instance\n | (string & {});\n\n/**\n * Model specifier - can be a string like \"openai/gpt-4o\" or a LanguageModel instance\n */\nexport type ModelSpecifier = string | LanguageModel;\n\n/**\n * MCP Client configuration for HTTP transport\n */\nexport interface MCPClientConfigHTTP {\n /**\n * Type of MCP client\n */\n type: \"http\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional transport options for HTTP client\n */\n options?: StreamableHTTPClientTransportOptions;\n}\n\n/**\n * MCP Client configuration for SSE transport\n */\nexport interface MCPClientConfigSSE {\n /**\n * Type of MCP client\n */\n type: \"sse\";\n /**\n * URL of the MCP server\n */\n url: string;\n /**\n * Optional HTTP headers (e.g., for authentication)\n */\n headers?: Record<string, string>;\n}\n\n/**\n * MCP Client configuration\n */\nexport type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;\n\n/**\n * A user-managed MCP client that provides tools to the agent.\n * The user is responsible for creating, configuring, and closing the client.\n * Compatible with the return type of @ai-sdk/mcp's createMCPClient().\n *\n * Unlike mcpServers, the agent does NOT create or close these clients.\n * This allows persistent connections, custom auth, and tool caching.\n */\nexport interface MCPClientProvider {\n /** Return tools to be merged into the agent's tool set. */\n tools(): Promise<ToolSet>;\n}\n\n/**\n * Resolves a model specifier to a LanguageModel instance\n * @param spec - Model string (e.g., \"openai/gpt-4o\") or LanguageModel instance\n * @param apiKey - Optional API key to use instead of environment variables\n * @returns LanguageModel instance\n */\nexport function resolveModel(\n spec: ModelSpecifier,\n apiKey?: string,\n): LanguageModel {\n // If already a LanguageModel instance, pass through\n if (typeof spec !== \"string\") {\n return spec;\n }\n\n // Normalize \"provider/model\" or \"provider:model\" format\n const normalized = spec.replace(\"/\", \":\").trim();\n const parts = normalized.split(\":\");\n const rawProvider = parts[0];\n const rest = parts.slice(1);\n\n if (!rawProvider) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n const provider = rawProvider.toLowerCase();\n const model = rest.join(\":\").trim();\n\n if (!model) {\n throw new Error(\n `Invalid model string \"${spec}\". Use \"openai/gpt-5\", \"anthropic/claude-sonnet-4.5\", or \"google/gemini-2.5-pro\".`,\n );\n }\n\n switch (provider) {\n case \"openai\": {\n // Lazily create OpenAI provider\n // Use provided apiKey, or fall back to environment variable\n const openai = createOpenAI({\n apiKey: apiKey || process.env.OPENAI_API_KEY!,\n });\n // Accepts any OpenAI model id, e.g. \"gpt-4o\", \"gpt-4.1-mini\", \"o3-mini\"\n return openai(model);\n }\n\n case \"anthropic\": {\n // Lazily create Anthropic provider\n // Use provided apiKey, or fall back to environment variable\n const anthropic = createAnthropic({\n apiKey: apiKey || process.env.ANTHROPIC_API_KEY!,\n });\n // Accepts any Claude id, e.g. \"claude-3.7-sonnet\", \"claude-3.5-haiku\"\n return anthropic(model);\n }\n\n case \"google\":\n case \"gemini\":\n case \"google-gemini\": {\n // Lazily create Google provider\n // Use provided apiKey, or fall back to environment variable\n const google = createGoogleGenerativeAI({\n apiKey: apiKey || process.env.GOOGLE_API_KEY!,\n });\n // Accepts any Gemini id, e.g. \"gemini-2.5-pro\", \"gemini-2.5-flash\"\n return google(model);\n }\n\n case \"vertex\": {\n const vertex = createVertex();\n return vertex(model);\n }\n\n default:\n throw new Error(\n `Unknown provider \"${provider}\" in \"${spec}\". Supported: openai, anthropic, google (gemini).`,\n );\n }\n}\n\n/**\n * Tool definition for BuiltInAgent\n */\nexport interface ToolDefinition<\n TParameters extends StandardSchemaV1 = StandardSchemaV1,\n> {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}\n\n/**\n * Define a tool for use with BuiltInAgent\n * @param name - The name of the tool\n * @param description - Description of what the tool does\n * @param parameters - Schema for the tool's input parameters (any Standard Schema V1 compatible library: Zod, Valibot, ArkType, etc.)\n * @param execute - Function to execute the tool server-side\n * @returns Tool definition\n */\nexport function defineTool<TParameters extends StandardSchemaV1>(config: {\n name: string;\n description: string;\n parameters: TParameters;\n execute: (args: InferSchemaOutput<TParameters>) => Promise<unknown>;\n}): ToolDefinition<TParameters> {\n return {\n name: config.name,\n description: config.description,\n parameters: config.parameters,\n execute: config.execute,\n };\n}\n\ntype AGUIUserMessage = Extract<Message, { role: \"user\" }>;\n\nfunction flattenUserMessageContent(\n content?: AGUIUserMessage[\"content\"],\n): string {\n if (!content) {\n return \"\";\n }\n\n if (typeof content === \"string\") {\n return content;\n }\n\n return content\n .map((part) => {\n if (\n part &&\n typeof part === \"object\" &&\n \"type\" in part &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n return \"\";\n })\n .filter((text) => text.length > 0)\n .join(\"\\n\");\n}\n\n/**\n * Options for converting AG-UI messages to Vercel AI SDK format\n */\nexport interface MessageConversionOptions {\n forwardSystemMessages?: boolean;\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to Vercel AI SDK ModelMessage format\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n): ModelMessage[] {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\n\n for (const toolCall of message.toolCalls ?? []) {\n const toolCallPart: ToolCallPart = {\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: safeParseToolArgs(toolCall.function.arguments),\n };\n parts.push(toolCallPart);\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: flattenUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n let toolName = \"unknown\";\n // Find the tool name from the corresponding tool call\n for (const msg of messages) {\n if (msg.role === \"assistant\") {\n for (const toolCall of msg.toolCalls ?? []) {\n if (toolCall.id === message.toolCallId) {\n toolName = toolCall.function.name;\n break;\n }\n }\n }\n }\n\n const toolResultPart: ToolResultPart = {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName: toolName,\n output: {\n type: \"text\",\n value: message.content,\n },\n };\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [toolResultPart],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * JSON Schema type definition\n */\ninterface JsonSchema {\n type: \"object\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"array\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n}\n\n/**\n * Converts JSON Schema to Zod schema\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(\n value,\n jsonSchema.required ? jsonSchema.required.includes(key) : false,\n );\n }\n const schema = z.object(spec).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = z\n .enum(jsonSchema.enum as [string, ...string[]])\n .describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n const schema = z.string().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = z.number().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const schema = z.boolean().describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = z.array(itemSchema).describe(jsonSchema.description ?? \"\");\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\n throw new Error(\"Invalid JSON schema\");\n}\n\n/**\n * Converts AG-UI tools to Vercel AI SDK ToolSet\n */\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n const schema = obj as Record<string, unknown>;\n // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(schema).length === 0) return true;\n return (\n typeof schema.type === \"string\" &&\n [\"object\", \"string\", \"number\", \"integer\", \"boolean\", \"array\"].includes(\n schema.type,\n )\n );\n}\n\nexport function convertToolsToVercelAITools(\n tools: RunAgentInput[\"tools\"],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const zodSchema = convertJsonSchemaToZodSchema(tool.parameters, true);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: zodSchema,\n });\n }\n\n return result;\n}\n\n/**\n * Check whether a schema is a Zod schema by inspecting its Standard Schema vendor.\n */\nfunction isZodSchema(schema: StandardSchemaV1): boolean {\n return schema[\"~standard\"]?.vendor === \"zod\";\n}\n\n/**\n * Converts ToolDefinition array to Vercel AI SDK ToolSet.\n *\n * For Zod schemas, passes them directly to the AI SDK (Zod satisfies FlexibleSchema).\n * For non-Zod schemas, converts to JSON Schema via schemaToJsonSchema() and wraps\n * with the AI SDK's jsonSchema() helper.\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: ToolDefinition[],\n): ToolSet {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n\n for (const tool of tools) {\n if (isZodSchema(tool.parameters)) {\n // Zod schemas can be passed directly to AI SDK (satisfies FlexibleSchema)\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: tool.parameters as any,\n execute: tool.execute,\n });\n } else {\n // Non-Zod: convert to JSON Schema and wrap with AI SDK's jsonSchema()\n const jsonSchemaObj = schemaToJsonSchema(tool.parameters);\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n inputSchema: aiJsonSchema(jsonSchemaObj),\n execute: tool.execute,\n });\n }\n }\n\n return result;\n}\n\n/**\n * Configuration for BuiltInAgent\n */\nexport interface BuiltInAgentConfiguration {\n /**\n * The model to use\n */\n model: BuiltInAgentModel | LanguageModel;\n /**\n * API key for the model provider (OpenAI, Anthropic, Google)\n * If not provided, falls back to environment variables:\n * - OPENAI_API_KEY for OpenAI models\n * - ANTHROPIC_API_KEY for Anthropic models\n * - GOOGLE_API_KEY for Google models\n */\n apiKey?: string;\n /**\n * Maximum number of steps/iterations for tool calling (default: 1)\n */\n maxSteps?: number;\n /**\n * Tool choice setting - how tools are selected for execution (default: \"auto\")\n */\n toolChoice?: ToolChoice<Record<string, unknown>>;\n /**\n * Maximum number of tokens to generate\n */\n maxOutputTokens?: number;\n /**\n * Temperature setting (range depends on provider)\n */\n temperature?: number;\n /**\n * Nucleus sampling (topP)\n */\n topP?: number;\n /**\n * Top K sampling\n */\n topK?: number;\n /**\n * Presence penalty\n */\n presencePenalty?: number;\n /**\n * Frequency penalty\n */\n frequencyPenalty?: number;\n /**\n * Sequences that will stop the generation\n */\n stopSequences?: string[];\n /**\n * Seed for deterministic results\n */\n seed?: number;\n /**\n * Maximum number of retries\n */\n maxRetries?: number;\n /**\n * Prompt for the agent\n */\n prompt?: string;\n /**\n * List of properties that can be overridden by forwardedProps.\n */\n overridableProperties?: OverridableProperty[];\n /**\n * Optional list of MCP server configurations\n */\n mcpServers?: MCPClientConfig[];\n /**\n * Optional list of user-managed MCP clients.\n * Unlike mcpServers, the agent does NOT create or close these clients.\n * The user controls the lifecycle, persistence, auth, and caching.\n *\n * Compatible with @ai-sdk/mcp's createMCPClient() return type:\n * ```typescript\n * const client = await createMCPClient({ transport });\n * const agent = new BuiltInAgent({ model: \"...\", mcpClients: [client] });\n * ```\n */\n mcpClients?: MCPClientProvider[];\n /**\n * Optional tools available to the agent\n */\n tools?: ToolDefinition[];\n /**\n * Forward system-role messages from input to the LLM.\n * Default: false\n */\n forwardSystemMessages?: boolean;\n /**\n * Forward developer-role messages from input to the LLM (as system messages).\n * Default: false\n */\n forwardDeveloperMessages?: boolean;\n /**\n * Provider-specific options passed to the model (e.g., OpenAI reasoningEffort).\n * Example: `{ openai: { reasoningEffort: \"high\" } }`\n */\n providerOptions?: Record<string, any>;\n}\n\nexport class BuiltInAgent extends AbstractAgent {\n private abortController?: AbortController;\n\n constructor(private config: BuiltInAgentConfiguration) {\n super();\n }\n\n /**\n * Check if a property can be overridden by forwardedProps\n */\n canOverride(property: OverridableProperty): boolean {\n return this.config?.overridableProperties?.includes(property) ?? false;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n return new Observable<BaseEvent>((subscriber) => {\n // Emit RUN_STARTED event\n const startEvent: RunStartedEvent = {\n type: EventType.RUN_STARTED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(startEvent);\n\n // Resolve the model, passing API key if provided\n const model = resolveModel(this.config.model, this.config.apiKey);\n\n // Build prompt based on conditions\n let systemPrompt: string | undefined = undefined;\n\n // Check if we should build a prompt:\n // - config.prompt is set, OR\n // - input.context is non-empty, OR\n // - input.state is non-empty and not an empty object\n const hasPrompt = !!this.config.prompt;\n const hasContext = input.context && input.context.length > 0;\n const hasState =\n input.state !== undefined &&\n input.state !== null &&\n !(\n typeof input.state === \"object\" &&\n Object.keys(input.state).length === 0\n );\n\n if (hasPrompt || hasContext || hasState) {\n const parts: string[] = [];\n\n // First: the prompt if any\n if (hasPrompt) {\n parts.push(this.config.prompt!);\n }\n\n // Second: context from the application\n if (hasContext) {\n parts.push(\"\\n## Context from the application\\n\");\n for (const ctx of input.context) {\n parts.push(`${ctx.description}:\\n${ctx.value}\\n`);\n }\n }\n\n // Third: state from the application that can be edited\n if (hasState) {\n parts.push(\n \"\\n## Application State\\n\" +\n \"This is state from the application that you can edit by calling AGUISendStateSnapshot or AGUISendStateDelta.\\n\" +\n `\\`\\`\\`json\\n${JSON.stringify(input.state, null, 2)}\\n\\`\\`\\`\\n`,\n );\n }\n\n systemPrompt = parts.join(\"\");\n }\n\n // Convert messages and prepend system message if we have a prompt\n const messages = convertMessagesToVercelAISDKMessages(input.messages, {\n forwardSystemMessages: this.config.forwardSystemMessages,\n forwardDeveloperMessages: this.config.forwardDeveloperMessages,\n });\n if (systemPrompt) {\n messages.unshift({\n role: \"system\",\n content: systemPrompt,\n });\n }\n\n // Merge tools from input and config\n let allTools: ToolSet = convertToolsToVercelAITools(input.tools);\n if (this.config.tools && this.config.tools.length > 0) {\n const configTools = convertToolDefinitionsToVercelAITools(\n this.config.tools,\n );\n allTools = { ...allTools, ...configTools };\n }\n\n const streamTextParams: Parameters<typeof streamText>[0] = {\n model,\n messages,\n tools: allTools,\n toolChoice: this.config.toolChoice,\n stopWhen: this.config.maxSteps\n ? stepCountIs(this.config.maxSteps)\n : undefined,\n maxOutputTokens: this.config.maxOutputTokens,\n temperature: this.config.temperature,\n topP: this.config.topP,\n topK: this.config.topK,\n presencePenalty: this.config.presencePenalty,\n frequencyPenalty: this.config.frequencyPenalty,\n stopSequences: this.config.stopSequences,\n seed: this.config.seed,\n providerOptions: this.config.providerOptions,\n maxRetries: this.config.maxRetries,\n };\n\n // Apply forwardedProps overrides (if allowed)\n if (input.forwardedProps && typeof input.forwardedProps === \"object\") {\n const props = input.forwardedProps as Record<string, unknown>;\n\n // Check and apply each overridable property\n if (props.model !== undefined && this.canOverride(\"model\")) {\n if (\n typeof props.model === \"string\" ||\n typeof props.model === \"object\"\n ) {\n // Accept any string or LanguageModel instance for model override\n // Use the configured API key when resolving overridden models\n streamTextParams.model = resolveModel(\n props.model as string | LanguageModel,\n this.config.apiKey,\n );\n }\n }\n if (props.toolChoice !== undefined && this.canOverride(\"toolChoice\")) {\n // ToolChoice can be 'auto', 'required', 'none', or { type: 'tool', toolName: string }\n const toolChoice = props.toolChoice;\n if (\n toolChoice === \"auto\" ||\n toolChoice === \"required\" ||\n toolChoice === \"none\" ||\n (typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n \"type\" in toolChoice &&\n toolChoice.type === \"tool\")\n ) {\n streamTextParams.toolChoice = toolChoice as ToolChoice<\n Record<string, unknown>\n >;\n }\n }\n if (\n typeof props.maxOutputTokens === \"number\" &&\n this.canOverride(\"maxOutputTokens\")\n ) {\n streamTextParams.maxOutputTokens = props.maxOutputTokens;\n }\n if (\n typeof props.temperature === \"number\" &&\n this.canOverride(\"temperature\")\n ) {\n streamTextParams.temperature = props.temperature;\n }\n if (typeof props.topP === \"number\" && this.canOverride(\"topP\")) {\n streamTextParams.topP = props.topP;\n }\n if (typeof props.topK === \"number\" && this.canOverride(\"topK\")) {\n streamTextParams.topK = props.topK;\n }\n if (\n typeof props.presencePenalty === \"number\" &&\n this.canOverride(\"presencePenalty\")\n ) {\n streamTextParams.presencePenalty = props.presencePenalty;\n }\n if (\n typeof props.frequencyPenalty === \"number\" &&\n this.canOverride(\"frequencyPenalty\")\n ) {\n streamTextParams.frequencyPenalty = props.frequencyPenalty;\n }\n if (\n Array.isArray(props.stopSequences) &&\n this.canOverride(\"stopSequences\")\n ) {\n // Validate all elements are strings\n if (\n props.stopSequences.every(\n (item): item is string => typeof item === \"string\",\n )\n ) {\n streamTextParams.stopSequences = props.stopSequences;\n }\n }\n if (typeof props.seed === \"number\" && this.canOverride(\"seed\")) {\n streamTextParams.seed = props.seed;\n }\n if (\n typeof props.maxRetries === \"number\" &&\n this.canOverride(\"maxRetries\")\n ) {\n streamTextParams.maxRetries = props.maxRetries;\n }\n if (\n props.providerOptions !== undefined &&\n this.canOverride(\"providerOptions\")\n ) {\n if (\n typeof props.providerOptions === \"object\" &&\n props.providerOptions !== null\n ) {\n streamTextParams.providerOptions = props.providerOptions as Record<\n string,\n any\n >;\n }\n }\n }\n\n // Set up MCP clients if configured and process the stream\n const mcpClients: Array<{ close: () => Promise<void> }> = [];\n\n (async () => {\n const abortController = new AbortController();\n this.abortController = abortController;\n let terminalEventEmitted = false;\n\n try {\n // Add AG-UI state update tools\n streamTextParams.tools = {\n ...streamTextParams.tools,\n AGUISendStateSnapshot: createVercelAISDKTool({\n description:\n \"Replace the entire application state with a new snapshot\",\n inputSchema: z.object({\n snapshot: z.any().describe(\"The complete new state object\"),\n }),\n execute: async ({ snapshot }) => {\n return { success: true, snapshot };\n },\n }),\n AGUISendStateDelta: createVercelAISDKTool({\n description:\n \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: z.object({\n delta: z\n .array(\n z.object({\n op: z\n .enum([\"add\", \"replace\", \"remove\"])\n .describe(\"The operation to perform\"),\n path: z\n .string()\n .describe(\"JSON Pointer path (e.g., '/foo/bar')\"),\n value: z\n .any()\n .optional()\n .describe(\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n ),\n }),\n )\n .describe(\"Array of JSON Patch operations\"),\n }),\n execute: async ({ delta }) => {\n return { success: true, delta };\n },\n }),\n };\n\n // Merge tools from user-managed MCP clients (user controls lifecycle)\n if (this.config.mcpClients && this.config.mcpClients.length > 0) {\n for (const client of this.config.mcpClients) {\n const mcpTools = await client.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n\n // Initialize MCP clients and get their tools\n if (this.config.mcpServers && this.config.mcpServers.length > 0) {\n for (const serverConfig of this.config.mcpServers) {\n let transport;\n\n if (serverConfig.type === \"http\") {\n const url = new URL(serverConfig.url);\n transport = new StreamableHTTPClientTransport(\n url,\n serverConfig.options,\n );\n } else if (serverConfig.type === \"sse\") {\n transport = new SSEClientTransport(\n new URL(serverConfig.url),\n serverConfig.headers,\n );\n }\n\n if (transport) {\n const mcpClient = await createMCPClient({ transport });\n mcpClients.push(mcpClient);\n\n // Get tools from this MCP server and merge with existing tools\n const mcpTools = await mcpClient.tools();\n streamTextParams.tools = {\n ...streamTextParams.tools,\n ...mcpTools,\n } as ToolSet;\n }\n }\n }\n\n // Call streamText and process the stream\n const response = streamText({\n ...streamTextParams,\n abortSignal: abortController.signal,\n });\n\n let messageId = randomUUID();\n let reasoningMessageId = randomUUID();\n\n const toolCallStates = new Map<\n string,\n {\n started: boolean;\n hasArgsDelta: boolean;\n ended: boolean;\n toolName?: string;\n }\n >();\n\n const ensureToolCallState = (toolCallId: string) => {\n let state = toolCallStates.get(toolCallId);\n if (!state) {\n state = { started: false, hasArgsDelta: false, ended: false };\n toolCallStates.set(toolCallId, state);\n }\n return state;\n };\n\n // Process fullStream events\n for await (const part of response.fullStream) {\n switch (part.type) {\n case \"abort\": {\n const abortEndEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(abortEndEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n case \"reasoning-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n if (providedId && providedId !== \"0\") {\n reasoningMessageId = providedId as typeof reasoningMessageId;\n }\n const reasoningStartEvent: ReasoningStartEvent = {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningStartEvent);\n const reasoningMessageStart: ReasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: \"reasoning\",\n };\n subscriber.next(reasoningMessageStart);\n break;\n }\n case \"reasoning-delta\": {\n const reasoningDeltaEvent: ReasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta:\n (\"text\" in part ? part.text : (part as any).delta) ?? \"\",\n };\n subscriber.next(reasoningDeltaEvent);\n break;\n }\n case \"reasoning-end\": {\n const reasoningMessageEnd: ReasoningMessageEndEvent = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningMessageEnd);\n const reasoningEndEvent: ReasoningEndEvent = {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n };\n subscriber.next(reasoningEndEvent);\n break;\n }\n case \"tool-input-start\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName;\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n break;\n }\n\n case \"tool-input-delta\": {\n const toolCallId = part.id;\n const state = ensureToolCallState(toolCallId);\n state.hasArgsDelta = true;\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: part.delta,\n };\n subscriber.next(argsEvent);\n break;\n }\n\n case \"tool-input-end\": {\n // No direct event – the subsequent \"tool-call\" part marks completion.\n break;\n }\n\n case \"text-start\": {\n // New text message starting - use the SDK-provided id\n // Use randomUUID() if part.id is falsy or \"0\" to prevent message merging issues\n const providedId = \"id\" in part ? part.id : undefined;\n messageId =\n providedId && providedId !== \"0\"\n ? (providedId as typeof messageId)\n : randomUUID();\n break;\n }\n\n case \"text-delta\": {\n // Accumulate text content - in AI SDK 5.0, the property is 'text'\n const textDelta = \"text\" in part ? part.text : \"\";\n // Emit text chunk event\n const textEvent: TextMessageChunkEvent = {\n type: EventType.TEXT_MESSAGE_CHUNK,\n role: \"assistant\",\n messageId,\n delta: textDelta,\n };\n subscriber.next(textEvent);\n break;\n }\n\n case \"tool-call\": {\n const toolCallId = part.toolCallId;\n const state = ensureToolCallState(toolCallId);\n state.toolName = part.toolName ?? state.toolName;\n\n if (!state.started) {\n state.started = true;\n const startEvent: ToolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n parentMessageId: messageId,\n toolCallId,\n toolCallName: part.toolName,\n };\n subscriber.next(startEvent);\n }\n\n if (\n !state.hasArgsDelta &&\n \"input\" in part &&\n part.input !== undefined\n ) {\n let serializedInput = \"\";\n if (typeof part.input === \"string\") {\n serializedInput = part.input;\n } else {\n try {\n serializedInput = JSON.stringify(part.input);\n } catch {\n serializedInput = String(part.input);\n }\n }\n\n if (serializedInput.length > 0) {\n const argsEvent: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n delta: serializedInput,\n };\n subscriber.next(argsEvent);\n state.hasArgsDelta = true;\n }\n }\n\n if (!state.ended) {\n state.ended = true;\n const endEvent: ToolCallEndEvent = {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n };\n subscriber.next(endEvent);\n }\n break;\n }\n\n case \"tool-result\": {\n const toolResult = \"output\" in part ? part.output : null;\n const toolName = \"toolName\" in part ? part.toolName : \"\";\n toolCallStates.delete(part.toolCallId);\n\n // Check if this is a state update tool\n if (\n toolName === \"AGUISendStateSnapshot\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateSnapshotEvent\n const stateSnapshotEvent: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: toolResult.snapshot,\n };\n subscriber.next(stateSnapshotEvent);\n } else if (\n toolName === \"AGUISendStateDelta\" &&\n toolResult &&\n typeof toolResult === \"object\"\n ) {\n // Emit StateDeltaEvent\n const stateDeltaEvent: StateDeltaEvent = {\n type: EventType.STATE_DELTA,\n delta: toolResult.delta,\n };\n subscriber.next(stateDeltaEvent);\n }\n\n // Always emit the tool result event for the LLM\n const resultEvent: ToolCallResultEvent = {\n type: EventType.TOOL_CALL_RESULT,\n role: \"tool\",\n messageId: randomUUID(),\n toolCallId: part.toolCallId,\n content: JSON.stringify(toolResult),\n };\n subscriber.next(resultEvent);\n break;\n }\n\n case \"finish\": {\n // Emit run finished event\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n terminalEventEmitted = true;\n\n // Complete the observable\n subscriber.complete();\n break;\n }\n\n case \"error\": {\n if (abortController.signal.aborted) {\n break;\n }\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: part.error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n\n // Handle error\n subscriber.error(part.error);\n break;\n }\n }\n }\n\n if (!terminalEventEmitted) {\n if (abortController.signal.aborted) {\n // Let the runner finalize the stream on stop requests so it can\n // inject consistent closing events and a RUN_FINISHED marker.\n } else {\n const finishedEvent: RunFinishedEvent = {\n type: EventType.RUN_FINISHED,\n threadId: input.threadId,\n runId: input.runId,\n };\n subscriber.next(finishedEvent);\n }\n\n terminalEventEmitted = true;\n subscriber.complete();\n }\n } catch (error) {\n if (abortController.signal.aborted) {\n subscriber.complete();\n } else {\n const runErrorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: error + \"\",\n };\n subscriber.next(runErrorEvent);\n terminalEventEmitted = true;\n subscriber.error(error);\n }\n } finally {\n this.abortController = undefined;\n await Promise.all(mcpClients.map((client) => client.close()));\n }\n })();\n\n // Cleanup function\n return () => {\n // Cleanup MCP clients if stream is unsubscribed\n Promise.all(mcpClients.map((client) => client.close())).catch(() => {\n // Ignore cleanup errors\n });\n };\n });\n }\n\n clone() {\n const cloned = new BuiltInAgent(this.config);\n // Copy middlewares from parent class\n // @ts-expect-error - accessing protected property from parent\n cloned.middlewares = [...this.middlewares];\n return cloned;\n }\n\n abortRun(): void {\n this.abortController?.abort();\n }\n}\n\n/**\n * @deprecated Use BuiltInAgent instead\n */\nexport class BasicAgent extends BuiltInAgent {\n constructor(config: BuiltInAgentConfiguration) {\n super(config);\n console.warn(\"BasicAgent is deprecated, use BuiltInAgent instead\");\n }\n}\n\nexport type BasicAgentConfiguration = BuiltInAgentConfiguration;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6KA,SA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AAC9B,6BAAuB;AACvB,iBAAW,MAAM,MAAM;;cAEjB;AACR,UAAK,kBAAkB;AACvB,WAAM,QAAQ,IAAI,WAAW,KAAK,WAAW,OAAO,OAAO,CAAC,CAAC;;OAE7D;AAGJ,gBAAa;AAEX,YAAQ,IAAI,WAAW,KAAK,WAAW,OAAO,OAAO,CAAC,CAAC,CAAC,YAAY,GAElE;;IAEJ;;CAGJ,QAAQ;EACN,MAAM,SAAS,IAAI,aAAa,KAAK,OAAO;AAG5C,SAAO,cAAc,CAAC,GAAG,KAAK,YAAY;AAC1C,SAAO;;CAGT,WAAiB;AACf,OAAK,iBAAiB,OAAO;;;;;;AAOjC,IAAa,aAAb,cAAgC,aAAa;CAC3C,YAAY,QAAmC;AAC7C,QAAM,OAAO;AACb,UAAQ,KAAK,qDAAqD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkitnext/agent",
|
|
3
|
-
"version": "1.54.1-next.
|
|
3
|
+
"version": "1.54.1-next.5",
|
|
4
4
|
"deprecated": "This package is deprecated. Use @copilotkit/agent instead. V2 features are being integrated into the main @copilotkit exports and will be available under the /v2 subpath.",
|
|
5
5
|
"description": "Basic Agent for CopilotKit",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -26,11 +26,11 @@
|
|
|
26
26
|
"typescript": "5.8.2",
|
|
27
27
|
"valibot": "^1.2.0",
|
|
28
28
|
"vitest": "^3.0.5",
|
|
29
|
-
"@copilotkitnext/eslint-config": "1.54.1-next.
|
|
30
|
-
"@copilotkitnext/typescript-config": "1.54.1-next.
|
|
29
|
+
"@copilotkitnext/eslint-config": "1.54.1-next.5",
|
|
30
|
+
"@copilotkitnext/typescript-config": "1.54.1-next.5"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@ag-ui/client": "0.0.
|
|
33
|
+
"@ag-ui/client": "0.0.48",
|
|
34
34
|
"@ai-sdk/anthropic": "^3.0.49",
|
|
35
35
|
"@ai-sdk/google": "^3.0.33",
|
|
36
36
|
"@ai-sdk/mcp": "^1.0.21",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"ai": "^6.0.104",
|
|
41
41
|
"rxjs": "7.8.1",
|
|
42
42
|
"zod": "^3.25.75",
|
|
43
|
-
"@copilotkitnext/shared": "1.54.1-next.
|
|
43
|
+
"@copilotkitnext/shared": "1.54.1-next.5"
|
|
44
44
|
},
|
|
45
45
|
"engines": {
|
|
46
46
|
"node": ">=18"
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
2
|
+
import { BasicAgent, type MCPClientProvider } from "../index";
|
|
3
|
+
import { EventType, type RunAgentInput } from "@ag-ui/client";
|
|
4
|
+
import { streamText, type ToolSet } from "ai";
|
|
5
|
+
import {
|
|
6
|
+
mockStreamTextResponse,
|
|
7
|
+
textDelta,
|
|
8
|
+
finish,
|
|
9
|
+
collectEvents,
|
|
10
|
+
} from "./test-helpers";
|
|
11
|
+
|
|
12
|
+
// Mock the ai module
|
|
13
|
+
vi.mock("ai", () => ({
|
|
14
|
+
streamText: vi.fn(),
|
|
15
|
+
tool: vi.fn((config) => config),
|
|
16
|
+
stepCountIs: vi.fn((count: number) => ({ type: "stepCount", count })),
|
|
17
|
+
}));
|
|
18
|
+
|
|
19
|
+
// Mock the SDK clients
|
|
20
|
+
vi.mock("@ai-sdk/openai", () => ({
|
|
21
|
+
createOpenAI: vi.fn(() => (modelId: string) => ({
|
|
22
|
+
modelId,
|
|
23
|
+
provider: "openai",
|
|
24
|
+
})),
|
|
25
|
+
}));
|
|
26
|
+
|
|
27
|
+
// Mock MCP imports so mcpServers code path doesn't fail when tested alongside mcpClients
|
|
28
|
+
vi.mock("@ai-sdk/mcp", () => ({
|
|
29
|
+
experimental_createMCPClient: vi.fn(),
|
|
30
|
+
}));
|
|
31
|
+
|
|
32
|
+
// Transport mocks must return truthy objects so `if (transport)` check passes in run()
|
|
33
|
+
vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({
|
|
34
|
+
StreamableHTTPClientTransport: vi.fn(() => ({ type: "mock-http-transport" })),
|
|
35
|
+
}));
|
|
36
|
+
|
|
37
|
+
vi.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({
|
|
38
|
+
SSEClientTransport: vi.fn(() => ({ type: "mock-sse-transport" })),
|
|
39
|
+
}));
|
|
40
|
+
|
|
41
|
+
describe("mcpClients — user-managed MCP clients", () => {
|
|
42
|
+
const originalEnv = process.env;
|
|
43
|
+
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
vi.clearAllMocks();
|
|
46
|
+
process.env = { ...originalEnv };
|
|
47
|
+
process.env.OPENAI_API_KEY = "test-key";
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
afterEach(() => {
|
|
51
|
+
process.env = originalEnv;
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const baseInput: RunAgentInput = {
|
|
55
|
+
threadId: "thread1",
|
|
56
|
+
runId: "run1",
|
|
57
|
+
messages: [],
|
|
58
|
+
tools: [],
|
|
59
|
+
context: [],
|
|
60
|
+
state: {},
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
function makeMockProvider(
|
|
64
|
+
tools: Record<string, any>,
|
|
65
|
+
): MCPClientProvider & { close: ReturnType<typeof vi.fn> } {
|
|
66
|
+
return {
|
|
67
|
+
tools: vi.fn().mockResolvedValue(tools),
|
|
68
|
+
close: vi.fn(),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
it("tools from mcpClients are passed to streamText", async () => {
|
|
73
|
+
const mockTools = {
|
|
74
|
+
listEnvelopes: { description: "List envelopes", execute: vi.fn() },
|
|
75
|
+
};
|
|
76
|
+
const provider = makeMockProvider(mockTools);
|
|
77
|
+
|
|
78
|
+
const agent = new BasicAgent({
|
|
79
|
+
model: "openai/gpt-4o",
|
|
80
|
+
mcpClients: [provider],
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
vi.mocked(streamText).mockReturnValue(
|
|
84
|
+
mockStreamTextResponse([textDelta("Hello"), finish()]) as any,
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
await collectEvents(agent["run"](baseInput));
|
|
88
|
+
|
|
89
|
+
const callArgs = vi.mocked(streamText).mock.calls[0][0];
|
|
90
|
+
expect(callArgs.tools).toHaveProperty("listEnvelopes");
|
|
91
|
+
expect(callArgs.tools.listEnvelopes.description).toBe("List envelopes");
|
|
92
|
+
expect(provider.tools).toHaveBeenCalledOnce();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("mcpClients are NOT closed after run completes", async () => {
|
|
96
|
+
const provider = makeMockProvider({
|
|
97
|
+
myTool: { description: "A tool", execute: vi.fn() },
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const agent = new BasicAgent({
|
|
101
|
+
model: "openai/gpt-4o",
|
|
102
|
+
mcpClients: [provider],
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
vi.mocked(streamText).mockReturnValue(
|
|
106
|
+
mockStreamTextResponse([finish()]) as any,
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
await collectEvents(agent["run"](baseInput));
|
|
110
|
+
|
|
111
|
+
expect(provider.close).not.toHaveBeenCalled();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("mcpServers tools override mcpClients tools on name collision", async () => {
|
|
115
|
+
const clientExecute = vi.fn();
|
|
116
|
+
const serverExecute = vi.fn();
|
|
117
|
+
|
|
118
|
+
const provider = makeMockProvider({
|
|
119
|
+
sharedTool: { description: "from client", execute: clientExecute },
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
// Mock mcpServers flow: createMCPClient returns a client with tools()
|
|
123
|
+
const { experimental_createMCPClient } = await import("@ai-sdk/mcp");
|
|
124
|
+
vi.mocked(experimental_createMCPClient).mockResolvedValue({
|
|
125
|
+
tools: vi.fn().mockResolvedValue({
|
|
126
|
+
sharedTool: { description: "from server", execute: serverExecute },
|
|
127
|
+
}),
|
|
128
|
+
close: vi.fn(),
|
|
129
|
+
} as any);
|
|
130
|
+
|
|
131
|
+
const agent = new BasicAgent({
|
|
132
|
+
model: "openai/gpt-4o",
|
|
133
|
+
mcpClients: [provider],
|
|
134
|
+
mcpServers: [{ type: "http", url: "http://localhost:9999" }],
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
vi.mocked(streamText).mockReturnValue(
|
|
138
|
+
mockStreamTextResponse([finish()]) as any,
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
await collectEvents(agent["run"](baseInput));
|
|
142
|
+
|
|
143
|
+
const callArgs = vi.mocked(streamText).mock.calls[0][0];
|
|
144
|
+
// mcpServers runs after mcpClients, so "from server" should win
|
|
145
|
+
expect(callArgs.tools.sharedTool.description).toBe("from server");
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("multiple mcpClients merge in order (later overrides earlier)", async () => {
|
|
149
|
+
const provider1 = makeMockProvider({
|
|
150
|
+
toolA: { description: "from provider 1", execute: vi.fn() },
|
|
151
|
+
shared: { description: "from provider 1", execute: vi.fn() },
|
|
152
|
+
});
|
|
153
|
+
const provider2 = makeMockProvider({
|
|
154
|
+
toolB: { description: "from provider 2", execute: vi.fn() },
|
|
155
|
+
shared: { description: "from provider 2", execute: vi.fn() },
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
const agent = new BasicAgent({
|
|
159
|
+
model: "openai/gpt-4o",
|
|
160
|
+
mcpClients: [provider1, provider2],
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
vi.mocked(streamText).mockReturnValue(
|
|
164
|
+
mockStreamTextResponse([finish()]) as any,
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
await collectEvents(agent["run"](baseInput));
|
|
168
|
+
|
|
169
|
+
const callArgs = vi.mocked(streamText).mock.calls[0][0];
|
|
170
|
+
expect(callArgs.tools).toHaveProperty("toolA");
|
|
171
|
+
expect(callArgs.tools).toHaveProperty("toolB");
|
|
172
|
+
expect(callArgs.tools.shared.description).toBe("from provider 2");
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it("empty mcpClients array is a no-op", async () => {
|
|
176
|
+
const agent = new BasicAgent({
|
|
177
|
+
model: "openai/gpt-4o",
|
|
178
|
+
mcpClients: [],
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
vi.mocked(streamText).mockReturnValue(
|
|
182
|
+
mockStreamTextResponse([textDelta("Hi"), finish()]) as any,
|
|
183
|
+
);
|
|
184
|
+
|
|
185
|
+
const events = await collectEvents(agent["run"](baseInput));
|
|
186
|
+
|
|
187
|
+
// Should still work normally
|
|
188
|
+
const textEvents = events.filter(
|
|
189
|
+
(e: any) => e.type === EventType.TEXT_MESSAGE_CHUNK,
|
|
190
|
+
);
|
|
191
|
+
expect(textEvents.length).toBeGreaterThan(0);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("mcpClients .tools() rejection emits RUN_ERROR", async () => {
|
|
195
|
+
const failingProvider: MCPClientProvider = {
|
|
196
|
+
tools: vi.fn().mockRejectedValue(new Error("MCP connection lost")),
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const agent = new BasicAgent({
|
|
200
|
+
model: "openai/gpt-4o",
|
|
201
|
+
mcpClients: [failingProvider],
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
vi.mocked(streamText).mockReturnValue(
|
|
205
|
+
mockStreamTextResponse([finish()]) as any,
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
// Collect events manually so we can capture RUN_ERROR before the rejection
|
|
209
|
+
const events: any[] = [];
|
|
210
|
+
try {
|
|
211
|
+
await new Promise((resolve, reject) => {
|
|
212
|
+
agent["run"](baseInput).subscribe({
|
|
213
|
+
next: (event: any) => events.push(event),
|
|
214
|
+
error: (err: any) => reject(err),
|
|
215
|
+
complete: () => resolve(events),
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
} catch {
|
|
219
|
+
// Expected — Observable errors after emitting RUN_ERROR
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// streamText should NOT have been called (error before reaching it)
|
|
223
|
+
expect(streamText).not.toHaveBeenCalled();
|
|
224
|
+
// A RUN_ERROR event should have been emitted
|
|
225
|
+
expect(events.some((e) => e.type === EventType.RUN_ERROR)).toBe(true);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("clone() shares the same mcpClients references", () => {
|
|
229
|
+
const provider = makeMockProvider({});
|
|
230
|
+
|
|
231
|
+
const agent = new BasicAgent({
|
|
232
|
+
model: "openai/gpt-4o",
|
|
233
|
+
mcpClients: [provider],
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
const cloned = agent.clone();
|
|
237
|
+
|
|
238
|
+
// Access the config to verify same reference
|
|
239
|
+
// Both agents share the same config object (by reference)
|
|
240
|
+
expect((cloned as any).config.mcpClients[0]).toBe(provider);
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
it("type compatibility: @ai-sdk/mcp MCPClient satisfies MCPClientProvider", async () => {
|
|
244
|
+
// This is a compile-time check — if MCPClientProvider's .tools() signature
|
|
245
|
+
// is incompatible with @ai-sdk/mcp's MCPClient.tools(), this file won't compile.
|
|
246
|
+
//
|
|
247
|
+
// We use a dynamic import + type assertion rather than a static import because
|
|
248
|
+
// @ai-sdk/mcp is mocked in this test file. The type check happens at compile time
|
|
249
|
+
// regardless.
|
|
250
|
+
type MCPClient = Awaited<
|
|
251
|
+
ReturnType<typeof import("@ai-sdk/mcp").experimental_createMCPClient>
|
|
252
|
+
>;
|
|
253
|
+
|
|
254
|
+
// If this line causes a type error, MCPClientProvider needs to be widened
|
|
255
|
+
const _assignable: MCPClientProvider = {} as MCPClient;
|
|
256
|
+
void _assignable; // suppress unused warning
|
|
257
|
+
|
|
258
|
+
expect(true).toBe(true); // runtime no-op
|
|
259
|
+
});
|
|
260
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -152,6 +152,19 @@ export interface MCPClientConfigSSE {
|
|
|
152
152
|
*/
|
|
153
153
|
export type MCPClientConfig = MCPClientConfigHTTP | MCPClientConfigSSE;
|
|
154
154
|
|
|
155
|
+
/**
|
|
156
|
+
* A user-managed MCP client that provides tools to the agent.
|
|
157
|
+
* The user is responsible for creating, configuring, and closing the client.
|
|
158
|
+
* Compatible with the return type of @ai-sdk/mcp's createMCPClient().
|
|
159
|
+
*
|
|
160
|
+
* Unlike mcpServers, the agent does NOT create or close these clients.
|
|
161
|
+
* This allows persistent connections, custom auth, and tool caching.
|
|
162
|
+
*/
|
|
163
|
+
export interface MCPClientProvider {
|
|
164
|
+
/** Return tools to be merged into the agent's tool set. */
|
|
165
|
+
tools(): Promise<ToolSet>;
|
|
166
|
+
}
|
|
167
|
+
|
|
155
168
|
/**
|
|
156
169
|
* Resolves a model specifier to a LanguageModel instance
|
|
157
170
|
* @param spec - Model string (e.g., "openai/gpt-4o") or LanguageModel instance
|
|
@@ -606,6 +619,18 @@ export interface BuiltInAgentConfiguration {
|
|
|
606
619
|
* Optional list of MCP server configurations
|
|
607
620
|
*/
|
|
608
621
|
mcpServers?: MCPClientConfig[];
|
|
622
|
+
/**
|
|
623
|
+
* Optional list of user-managed MCP clients.
|
|
624
|
+
* Unlike mcpServers, the agent does NOT create or close these clients.
|
|
625
|
+
* The user controls the lifecycle, persistence, auth, and caching.
|
|
626
|
+
*
|
|
627
|
+
* Compatible with @ai-sdk/mcp's createMCPClient() return type:
|
|
628
|
+
* ```typescript
|
|
629
|
+
* const client = await createMCPClient({ transport });
|
|
630
|
+
* const agent = new BuiltInAgent({ model: "...", mcpClients: [client] });
|
|
631
|
+
* ```
|
|
632
|
+
*/
|
|
633
|
+
mcpClients?: MCPClientProvider[];
|
|
609
634
|
/**
|
|
610
635
|
* Optional tools available to the agent
|
|
611
636
|
*/
|
|
@@ -894,6 +919,17 @@ export class BuiltInAgent extends AbstractAgent {
|
|
|
894
919
|
}),
|
|
895
920
|
};
|
|
896
921
|
|
|
922
|
+
// Merge tools from user-managed MCP clients (user controls lifecycle)
|
|
923
|
+
if (this.config.mcpClients && this.config.mcpClients.length > 0) {
|
|
924
|
+
for (const client of this.config.mcpClients) {
|
|
925
|
+
const mcpTools = await client.tools();
|
|
926
|
+
streamTextParams.tools = {
|
|
927
|
+
...streamTextParams.tools,
|
|
928
|
+
...mcpTools,
|
|
929
|
+
} as ToolSet;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
897
933
|
// Initialize MCP clients and get their tools
|
|
898
934
|
if (this.config.mcpServers && this.config.mcpServers.length > 0) {
|
|
899
935
|
for (const serverConfig of this.config.mcpServers) {
|