An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat: add support for AI SDK v5 dynamic tools
Yoshiki Miuraccb352af33a2
diff --git a/bun.lock b/bun.lockindex dfa114f5..82644506 100644--- a/bun.lock+++ b/bun.lock@@ -11,7 +11,7 @@"@ai-sdk/google": "^2.0.0-beta.13","@ai-sdk/groq": "^2.0.0-beta.6","@ai-sdk/openai": "^2.0.0-beta.11",- "@ai-sdk/react": "^2.0.0-beta.25",+ "@ai-sdk/react": "2.0.0-beta.29","@ai-sdk/xai": "^2.0.0-beta.10","@aws-sdk/client-s3": "^3.850.0","@paralleldrive/cuid2": "^2.2.2",@@ -38,7 +38,7 @@"@tailwindcss/typography": "^0.5.12","@upstash/redis": "^1.34.0","@vercel/analytics": "^1.5.0",- "ai": "^5.0.0-beta.25",+ "ai": "5.0.0-beta.29","class-variance-authority": "^0.7.1","clsx": "^2.1.0","cmdk": "1.0.0",@@ -103,7 +103,7 @@"@ai-sdk/fireworks": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/openai-compatible": "1.0.0-beta.8", "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.5" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-G+OxlpaB8BKuBXfnbxexLz04aj3HbRDeM5exr6m3++ujcGUB5hJ6QSd/SIXy9T5rQovo4/6jeAnd8Yt7KHoNGw=="],- "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.5" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-dnRUPzSLvp3xvIx6M4FIz4ht8dfL8JkPKwH+akj10im4zbxUii3c3TQ3BJLRdx2Gq/SeljE9H0dX7PDtVyIrbQ=="],+ "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.7" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-k7mheXS8u+N0URwE/E8zn2v14aWEzRfCPVMtCqkEwQSUKDipKVHHnbQ5FrXCupZsMWEa0ZepTsSbtH+XmXO4Og=="],"@ai-sdk/google": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.5" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-qdudxuA4PM9z3CTT2PM3yKXcmlG3U314xq9U4jMGdcqgIXcrEPxXYlmgHLKu5D7HX3g5u+/jh/d8sDE1Ene/wA=="],@@ -117,7 +117,7 @@"@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-4Dv/wiGZrvO6fI7P0yMLa4XZru0XW8LPibTObbkHBdweLUVGIze7aCfxxQeY44Uqcbl/h6/yBTkx2XmPtwf/Ow=="],- "@ai-sdk/react": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider-utils": "3.0.0-beta.5", "ai": "5.0.0-beta.25", "swr": "^2.2.5", "throttleit": "2.1.0" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "zod": "^3.25.76 || ^4" }, "optionalPeers": ["zod"] }, "sha512-3f3f/z3idsH+sctQJ7t0enFywzIbHXDM6a3tvdPMX1dI53mAsVfyhaHzz8WT9swW3Mmphj0i5fZCH4t78m0L4A=="],+ "@ai-sdk/react": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider-utils": "3.0.0-beta.7", "ai": "5.0.0-beta.29", "swr": "^2.2.5", "throttleit": "2.1.0" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "zod": "^3.25.76 || ^4" }, "optionalPeers": ["zod"] }, "sha512-W9oxjD3XB2aPohuIffQ+s4HJ99ubzp+0ptdjCEH/kSzgEXROKPcj30VCIMeOlX/eaC6TT+BzW/Ht5sbyQuIAgg=="],"@ai-sdk/xai": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/openai-compatible": "1.0.0-beta.8", "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.5" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-k5IaGFbsZlUAV5xTBjXl4FEJmkiz6jNjzgUD/o5GoPxl8ZkH/mkh9HX0oEhr5cz0loCtkf0DOzdIcsgnixPrIA=="],@@ -833,7 +833,7 @@"agent-base": ["[email protected]", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="],- "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "1.0.0-beta.11", "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.5", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4" }, "bin": { "ai": "dist/bin/ai.min.js" } }, "sha512-pbfFqtQvz7hiDw6TwUH75CK9FgrZFBsxqbW4yW0aqluHw3nRbhf0w1u2AMiYgvWMy8Xf8TkBbMtY4vyMc4neeA=="],+ "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "1.0.0-beta.15", "@ai-sdk/provider": "2.0.0-beta.1", "@ai-sdk/provider-utils": "3.0.0-beta.7", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4" }, "bin": { "ai": "dist/bin/ai.min.js" } }, "sha512-v4qMxh4diGxZ1hfo5Lc7rDbEQj8zicCZGMQr8imGHLWjmm/pMFYFKp9JQSR5+kXXyXqpE2RtMWYomAm7LmHMDA=="],"ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="],@@ -1961,6 +1961,10 @@"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],+ "@ai-sdk/gateway/@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-w1nMJegq98/TpVOUlYPehX/tyTmyx4b0NCWH2VMHF6hpnJjGuS3UfzkEAKTkHCWYbNZY038b4IkGDx24C0xNOA=="],++ "@ai-sdk/react/@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-w1nMJegq98/TpVOUlYPehX/tyTmyx4b0NCWH2VMHF6hpnJjGuS3UfzkEAKTkHCWYbNZY038b4IkGDx24C0xNOA=="],+"@asamuzakjp/css-color/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],"@aws-crypto/sha1-browser/@smithy/util-utf8": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],@@ -1995,6 +1999,8 @@"@typescript-eslint/visitor-keys/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw=="],+ "ai/@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "2.0.0-beta.1", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-w1nMJegq98/TpVOUlYPehX/tyTmyx4b0NCWH2VMHF6hpnJjGuS3UfzkEAKTkHCWYbNZY038b4IkGDx24C0xNOA=="],+"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],"chokidar/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],diff --git a/components/chat.tsx b/components/chat.tsxindex dfdb53dc..204796bf 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -56,7 +56,7 @@ export function Chat({api: '/api/chat',prepareSendMessagesRequest: ({ messages, trigger, messageId }) => {switch (trigger) {- case 'regenerate-assistant-message':+ case 'regenerate-message':// Find the message being regeneratedconst messageToRegenerate = messages.find(m => m.id === messageId)return {@@ -72,7 +72,7 @@ export function Chat({}}- case 'submit-user-message':+ case 'submit-message':default:// Only send the last messagereturn {@@ -295,7 +295,31 @@ export function Chat({toolCallId: stringresult: any}) => {- addToolResult({ toolCallId, output: result })+ // Find the tool name from the message parts+ let toolName = 'unknown'+ const allParts = messages.flatMap(m => m.parts || [])++ for (const part of allParts) {+ const p = part as any+ if (p.type === 'tool-call' && p.toolCallId === toolCallId) {+ toolName = p.toolName+ break+ } else if (+ p.type?.startsWith('tool-') &&+ p.toolCallId === toolCallId+ ) {+ toolName = p.type.substring(5) // Remove 'tool-' prefix+ break+ } else if (+ p.type === 'dynamic-tool' &&+ p.toolCallId === toolCallId+ ) {+ toolName = p.toolName+ break+ }+ }++ addToolResult({ tool: toolName, toolCallId, output: result })}}scrollContainerRef={scrollContainerRef}onUpdateMessage={handleUpdateAndReloadMessage}diff --git a/components/dynamic-tool-display.tsx b/components/dynamic-tool-display.tsxnew file mode 100644index 00000000..3cd2bd8f--- /dev/null+++ b/components/dynamic-tool-display.tsx@@ -0,0 +1,137 @@+'use client'++import React from 'react'++// This matches the structure from AI SDK v5+type DynamicToolPart =+ | {+ type: 'dynamic-tool'+ toolCallId: string+ toolName: string+ state: 'input-streaming'+ input: unknown+ }+ | {+ type: 'dynamic-tool'+ toolCallId: string+ toolName: string+ state: 'input-available'+ input: unknown+ }+ | {+ type: 'dynamic-tool'+ toolCallId: string+ toolName: string+ state: 'output-available'+ input: unknown+ output: unknown+ }+ | {+ type: 'dynamic-tool'+ toolCallId: string+ toolName: string+ state: 'output-error'+ input: unknown+ errorText: string+ }++interface DynamicToolDisplayProps {+ part: DynamicToolPart+}++export function DynamicToolDisplay({ part }: DynamicToolDisplayProps) {+ // Extract tool type from name+ const getToolType = (toolName: string) => {+ if (toolName.startsWith('mcp__')) {+ return 'MCP Tool'+ } else if (toolName.startsWith('dynamic__')) {+ return 'Dynamic Tool'+ }+ return 'Custom Tool'+ }++ // Extract display name from tool name+ const getDisplayName = (toolName: string) => {+ if (toolName.startsWith('mcp__')) {+ return toolName.substring(5).replace(/__/g, '.')+ } else if (toolName.startsWith('dynamic__')) {+ return toolName.substring(9)+ }+ return toolName+ }++ const toolType = getToolType(part.toolName)+ const displayName = getDisplayName(part.toolName)++ return (+ <div className="dynamic-tool-container rounded-lg border p-4 my-2">+ <div className="flex items-center gap-2 mb-2">+ <span className="text-sm font-medium text-muted-foreground">+ {toolType}+ </span>+ <span className="text-sm font-semibold">{displayName}</span>+ </div>++ {/* Input display */}+ {(part.state === 'input-streaming' ||+ part.state === 'input-available' ||+ part.state === 'output-available' ||+ part.state === 'output-error') && (+ <div className="mb-2">+ <div className="text-xs text-muted-foreground mb-1">Input:</div>+ <pre className="text-xs bg-muted p-2 rounded overflow-auto max-h-40">+ <code>{JSON.stringify(part.input, null, 2)}</code>+ </pre>+ </div>+ )}++ {/* Output display */}+ {part.state === 'output-available' && (+ <div className="mb-2">+ <div className="text-xs text-muted-foreground mb-1">Output:</div>+ <pre className="text-xs bg-muted p-2 rounded overflow-auto max-h-40">+ <code>{JSON.stringify(part.output, null, 2)}</code>+ </pre>+ </div>+ )}++ {/* Error display */}+ {part.state === 'output-error' && (+ <div className="mb-2">+ <div className="text-xs text-destructive mb-1">Error:</div>+ <div className="text-xs bg-destructive/10 text-destructive p-2 rounded">+ {part.errorText}+ </div>+ </div>+ )}++ {/* Status indicator */}+ <div className="flex items-center gap-2 mt-2">+ <div+ className={`h-2 w-2 rounded-full ${+ part.state === 'input-streaming'+ ? 'bg-blue-500 animate-pulse'+ : part.state === 'input-available'+ ? 'bg-blue-500'+ : part.state === 'output-available'+ ? 'bg-green-500'+ : part.state === 'output-error'+ ? 'bg-red-500'+ : 'bg-gray-300'+ }`}+ />+ <span className="text-xs text-muted-foreground">+ {part.state === 'input-streaming'+ ? 'Streaming...'+ : part.state === 'input-available'+ ? 'Processing...'+ : part.state === 'output-available'+ ? 'Complete'+ : part.state === 'output-error'+ ? 'Failed'+ : 'Unknown'}+ </span>+ </div>+ </div>+ )+}diff --git a/components/render-message.tsx b/components/render-message.tsxindex 1f34a1fb..aefd638d 100644--- a/components/render-message.tsx+++ b/components/render-message.tsx@@ -3,6 +3,7 @@ import { UseChatHelpers } from '@ai-sdk/react'import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'import { AnswerSection } from './answer-section'+import { DynamicToolDisplay } from './dynamic-tool-display'import { ReasoningSection } from './reasoning-section'import { ToolSection } from './tool-section'import { UserFileSection } from './user-file-section'@@ -96,6 +97,13 @@ export function RenderMessage({onQuerySelect={onQuerySelect}/>)+ case 'dynamic-tool':+ return (+ <DynamicToolDisplay+ key={`${messageId}-dynamic-tool-${index}`}+ part={part as any}+ />+ )case 'text':// Only show actions if this is the last part and it's a text partreturn (diff --git a/drizzle/0001_rename_mcp_to_dynamic.sql b/drizzle/0001_rename_mcp_to_dynamic.sqlnew file mode 100644index 00000000..f6f02cb0--- /dev/null+++ b/drizzle/0001_rename_mcp_to_dynamic.sql@@ -0,0 +1,7 @@+-- Rename MCP columns to dynamic tool columns+ALTER TABLE "parts" RENAME COLUMN "tool_mcp_input" TO "tool_dynamic_input";+ALTER TABLE "parts" RENAME COLUMN "tool_mcp_output" TO "tool_dynamic_output";++-- Add new columns for dynamic tool metadata+ALTER TABLE "parts" ADD COLUMN "tool_dynamic_name" varchar(256);+ALTER TABLE "parts" ADD COLUMN "tool_dynamic_type" varchar(256);\ No newline at end of filediff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.jsonindex 08a52f34..bcdf4713 100644--- a/drizzle/meta/_journal.json+++ b/drizzle/meta/_journal.json@@ -8,6 +8,13 @@"when": 1753666852574,"tag": "0000_perfect_ares","breakpoints": true+ },+ {+ "idx": 1,+ "version": "7",+ "when": 1753666852575,+ "tag": "0001_rename_mcp_to_dynamic",+ "breakpoints": true}]}diff --git a/lib/agents/researcher-with-dynamic-tools.ts b/lib/agents/researcher-with-dynamic-tools.tsnew file mode 100644index 00000000..a86c5ec9--- /dev/null+++ b/lib/agents/researcher-with-dynamic-tools.ts@@ -0,0 +1,126 @@+import { Experimental_Agent as Agent, stepCountIs } from 'ai'++import {+ createCustomTool,+ createDynamicTool,+ createMCPTool+} from '../tools/dynamic'+import { createQuestionTool } from '../tools/question'+import { retrieveTool } from '../tools/retrieve'+import { createSearchTool } from '../tools/search'+import { createVideoSearchTool } from '../tools/video-search'+import { getModel } from '../utils/registry'++const SYSTEM_PROMPT = `+Instructions:++You are a helpful AI assistant with access to real-time web search, content retrieval, video search capabilities, the ability to ask clarifying questions, and dynamic tools that may be added at runtime.++When asked a question, you should:+1. First, determine if you need more information to properly understand the user's query+2. **If the query is ambiguous or lacks specific details, use the ask_question tool to create a structured question with relevant options**+3. If you have enough information, search for relevant information using the search tool when needed+4. Use the retrieve tool to get detailed content from specific URLs+5. Use the video search tool when looking for video content+6. Use any available dynamic tools when they are relevant to the user's request+7. Analyze all search results to provide accurate, up-to-date information+8. Always cite sources using the [number](url) format, matching the order of search results. If multiple sources are relevant, include all of them, and comma separate them. Only use information that has a URL available for citation.+9. If results are not relevant or helpful, rely on your general knowledge+10. Provide comprehensive and detailed responses based on search results, ensuring thorough coverage of the user's question+11. Use markdown to structure your responses. Use headings to break up the content into sections.+12. **Use the retrieve tool only with user-provided URLs.**++When using the ask_question tool:+- Create clear, concise questions+- Provide relevant predefined options+- Enable free-form input when appropriate+- Match the language to the user's language (except option values which must be in English)++When using dynamic tools:+- Read the tool description carefully to understand its purpose+- Pass the appropriate parameters based on the tool's requirements+- Handle any errors gracefully and inform the user if a tool fails++Citation Format:+[number](url)+`++interface DynamicToolConfig {+ name: string+ description: string+ handler?: (params: any) => Promise<any>+ mcpClient?: any // Replace with actual MCP client type+}++export function researcherWithDynamicTools({+ model,+ searchMode,+ dynamicTools = []+}: {+ model: string+ searchMode: boolean+ dynamicTools?: DynamicToolConfig[]+}) {+ try {+ const currentDate = new Date().toLocaleString()++ // Create model-specific tools+ const searchTool = createSearchTool(model)+ const videoSearchTool = createVideoSearchTool(model)+ const askQuestionTool = createQuestionTool(model)++ // Create base tools object+ const tools: Record<string, any> = {+ search: searchTool,+ retrieve: retrieveTool,+ videoSearch: videoSearchTool,+ askQuestion: askQuestionTool+ }++ // Add dynamic tools+ dynamicTools.forEach(toolConfig => {+ if (toolConfig.mcpClient) {+ // MCP tool+ tools[toolConfig.name] = createMCPTool(+ toolConfig.name,+ toolConfig.description,+ toolConfig.mcpClient+ )+ } else if (toolConfig.handler) {+ // Custom dynamic tool+ tools[toolConfig.name] = createCustomTool(+ toolConfig.name,+ toolConfig.description,+ toolConfig.handler+ )+ } else {+ console.warn(+ `Dynamic tool ${toolConfig.name} has no handler or MCP client`+ )+ }+ })++ // Get list of all tool names for activeTools+ const allToolNames = Object.keys(tools)+ const activeToolNames = searchMode+ ? allToolNames.filter(+ name =>+ ['search', 'retrieve', 'videoSearch'].includes(name) ||+ name.startsWith('mcp__') ||+ name.startsWith('dynamic__')+ )+ : undefined++ // Return an agent instance+ return new Agent({+ model: getModel(model),+ system: `${SYSTEM_PROMPT}\nCurrent date and time: ${currentDate}`,+ tools,+ activeTools: activeToolNames,+ stopWhen: searchMode ? stepCountIs(10) : stepCountIs(1)+ })+ } catch (error) {+ console.error('Error in researcher with dynamic tools:', error)+ throw error+ }+}diff --git a/lib/db/migrations/0003_rename_mcp_to_dynamic.sql b/lib/db/migrations/0003_rename_mcp_to_dynamic.sqlnew file mode 100644index 00000000..1acb9851--- /dev/null+++ b/lib/db/migrations/0003_rename_mcp_to_dynamic.sql@@ -0,0 +1,11 @@+-- Rename MCP tool columns to dynamic tool columns+ALTER TABLE parts+ RENAME COLUMN tool_mcp_input TO tool_dynamic_input;++ALTER TABLE parts+ RENAME COLUMN tool_mcp_output TO tool_dynamic_output;++-- Add dynamic tool metadata columns for storing tool name and type+ALTER TABLE parts+ ADD COLUMN tool_dynamic_name VARCHAR(256),+ ADD COLUMN tool_dynamic_type VARCHAR(256);\ No newline at end of filediff --git a/lib/db/schema.ts b/lib/db/schema.tsindex 4033295d..a8cbf5cb 100644--- a/lib/db/schema.ts+++ b/lib/db/schema.ts@@ -136,8 +136,12 @@ export const parts = pgTable(tool_relatedQuestions_output: json('tool_related_questions_output').$type<any>(),- tool_mcp_input: json('tool_mcp_input').$type<any>(),- tool_mcp_output: json('tool_mcp_output').$type<any>(),++ // Dynamic tools (includes MCP and other runtime-defined tools)+ tool_dynamic_input: json('tool_dynamic_input').$type<any>(),+ tool_dynamic_output: json('tool_dynamic_output').$type<any>(),+ tool_dynamic_name: varchar('tool_dynamic_name', { length: VARCHAR_LENGTH }),+ tool_dynamic_type: varchar('tool_dynamic_type', { length: VARCHAR_LENGTH }),// Data parts (generic support)data_prefix: varchar('data_prefix', { length: VARCHAR_LENGTH }),diff --git a/lib/tools/dynamic.ts b/lib/tools/dynamic.tsnew file mode 100644index 00000000..3b5879a0--- /dev/null+++ b/lib/tools/dynamic.ts@@ -0,0 +1,52 @@+import { dynamicTool } from 'ai'+import { z } from 'zod'++/**+ * Creates a dynamic tool that can be used for runtime-defined tools+ * such as MCP tools or user-defined functions+ */+export function createDynamicTool(+ name: string,+ description: string,+ execute: (input: unknown) => Promise<unknown>+) {+ return dynamicTool({+ description,+ // Use a flexible schema that accepts any object+ inputSchema: z.object({}).passthrough(),+ execute: async input => {+ try {+ const result = await execute(input)+ return result+ } catch (error) {+ console.error(`Error executing dynamic tool ${name}:`, error)+ throw error+ }+ }+ })+}++/**+ * Example: Create an MCP tool wrapper+ */+export function createMCPTool(+ toolName: string,+ description: string,+ mcpClient: any // Replace with actual MCP client type+) {+ return createDynamicTool(`mcp__${toolName}`, description, async input => {+ // Execute the MCP tool+ return await mcpClient.callTool(toolName, input)+ })+}++/**+ * Example: Create a custom user-defined tool+ */+export function createCustomTool(+ name: string,+ description: string,+ handler: (params: any) => Promise<any>+) {+ return createDynamicTool(`dynamic__${name}`, description, handler)+}diff --git a/lib/types/ai.ts b/lib/types/ai.tsindex 37f37fcc..02a2a1ad 100644--- a/lib/types/ai.ts+++ b/lib/types/ai.ts@@ -20,6 +20,8 @@ export type UITools = {retrieve: InferUITool<typeof retrieveTool>videoSearch: InferUITool<typeof videoSearchTool>askQuestion: InferUITool<typeof askQuestionTool>+ // Dynamic tools will be added at runtime+ [key: string]: any}export type TextPart = {diff --git a/lib/types/message-persistence.ts b/lib/types/message-persistence.tsindex 9857065f..783b8785 100644--- a/lib/types/message-persistence.ts+++ b/lib/types/message-persistence.ts@@ -25,13 +25,16 @@ export type ToolState =| 'output-available'| 'output-error'-// MCP tool type definitions-export type MCPToolInput = {+// Dynamic tool type definitions (includes MCP and other runtime tools)+export type DynamicToolInput = {toolName: stringparams: unknown}-export type MCPToolOutput = unknown+export type DynamicToolOutput = unknown++// Dynamic tool type for storage+export type DynamicToolType = 'mcp' | 'dynamic' | 'custom'// Common MCP tool type definition examplesexport type MCPGitHubInput = {diff --git a/lib/utils/message-mapping.ts b/lib/utils/message-mapping.tsindex 6792a62e..4c27d0a2 100644--- a/lib/utils/message-mapping.ts+++ b/lib/utils/message-mapping.ts@@ -160,7 +160,7 @@ export function mapUIMessagePartsToDBParts(const toolName = getToolNameFromType(part.toolName)const toolInputColumn = `tool_${toolName}_input` as keyof DBMessagePart- return {+ const result: any = {...basePart,type: `tool-${toolName}`,tool_toolCallId: part.toolCallId,@@ -168,6 +168,16 @@ export function mapUIMessagePartsToDBParts([toolInputColumn]: part.args}+ // Store additional metadata for dynamic tools+ if (toolName === 'dynamic') {+ result.tool_dynamic_name = part.toolName+ result.tool_dynamic_type = part.toolName.startsWith('mcp__')+ ? 'mcp'+ : 'dynamic'+ }++ return result+case 'tool-result':const resultToolName = getToolNameFromCallId(part.toolCallId,@@ -176,7 +186,7 @@ export function mapUIMessagePartsToDBParts(const toolOutputColumn =`tool_${resultToolName}_output` as keyof DBMessagePart- return {+ const toolResult: any = {...basePart,type: `tool-${resultToolName}`,tool_toolCallId: part.toolCallId,@@ -187,6 +197,24 @@ export function mapUIMessagePartsToDBParts([toolOutputColumn]: !part.isError ? part.result : undefined}+ // Preserve dynamic tool metadata from the corresponding tool-call+ if (resultToolName === 'dynamic') {+ const toolCallPart = messageParts.find(+ p => isToolCallPart(p) && p.toolCallId === part.toolCallId+ ) as ToolCallPart | undefined++ if (toolCallPart) {+ toolResult.tool_dynamic_name = toolCallPart.toolName+ toolResult.tool_dynamic_type = toolCallPart.toolName.startsWith(+ 'mcp__'+ )+ ? 'mcp'+ : 'dynamic'+ }+ }++ return toolResult+// Step parts (for UI tracking)case 'step-start':case 'step-result':@@ -194,6 +222,29 @@ export function mapUIMessagePartsToDBParts(case 'step-finish':return null // These are not persisted+ // Dynamic tool parts from AI SDK v5+ case 'dynamic-tool':+ const dynamicPart = part as any+ return {+ ...basePart,+ type: 'tool-dynamic',+ tool_toolCallId: dynamicPart.toolCallId || generateId(),+ tool_state: dynamicPart.state as ToolState,+ tool_dynamic_name: dynamicPart.toolName,+ tool_dynamic_type: dynamicPart.toolName.startsWith('mcp__')+ ? 'mcp'+ : 'dynamic',+ tool_dynamic_input: dynamicPart.input,+ tool_dynamic_output:+ dynamicPart.state === 'output-available'+ ? dynamicPart.output+ : undefined,+ tool_errorText:+ dynamicPart.state === 'output-error'+ ? dynamicPart.errorText+ : undefined+ }+// Tool-specific parts that are not tool-call or tool-resultcase 'tool-search':case 'tool-retrieve':@@ -303,6 +354,19 @@ export function mapDBPartToUIMessagePart(const outputColumn =`tool_${toolName}_output` as keyof DBMessagePartSelect+ // Special handling for dynamic tools+ if (toolName === 'dynamic') {+ return {+ type: 'dynamic-tool',+ toolCallId: part.tool_toolCallId || '',+ toolName: part.tool_dynamic_name || '',+ state: part.tool_state as any, // Maps directly to AI SDK states+ input: part.tool_dynamic_input,+ output: part.tool_dynamic_output,+ errorText: part.tool_errorText+ }+ }+// Special handling for tool parts that maintain their typeif ([@@ -328,10 +392,16 @@ export function mapDBPartToUIMessagePart(part.tool_state === 'input-available' ||part.tool_state === 'input-streaming') {+ // For dynamic tools, use the stored original name+ const originalToolName =+ toolName === 'dynamic' && part.tool_dynamic_name+ ? part.tool_dynamic_name+ : getOriginalToolName(toolName)+return {type: 'tool-call',toolCallId: part.tool_toolCallId || '',- toolName: getOriginalToolName(toolName),+ toolName: originalToolName,args: part[inputColumn] as any}} else {@@ -377,9 +447,9 @@ function getToolNameFromType(toolName: string): string {relatedQuestions: 'relatedQuestions'}- // For MCP tools- if (toolName.startsWith('mcp__')) {- return 'mcp'+ // For dynamic tools (MCP and others)+ if (toolName.startsWith('mcp__') || toolName.startsWith('dynamic__')) {+ return 'dynamic'}return toolNameMap[toolName] || toolName@@ -414,7 +484,7 @@ function getOriginalToolName(dbToolName: string): string {retrieve: 'retrieve',question: 'askQuestion',videoSearch: 'videoSearch',- mcp: 'mcp' // For MCP, the actual tool name is included in the input+ dynamic: 'dynamic' // For dynamic tools, the actual tool name is stored separately}return reverseMap[dbToolName] || dbToolNamediff --git a/package.json b/package.jsonindex 28391f4d..1775113e 100644--- a/package.json+++ b/package.json@@ -23,7 +23,7 @@"@ai-sdk/google": "^2.0.0-beta.13","@ai-sdk/groq": "^2.0.0-beta.6","@ai-sdk/openai": "^2.0.0-beta.11",- "@ai-sdk/react": "^2.0.0-beta.25",+ "@ai-sdk/react": "2.0.0-beta.29","@ai-sdk/xai": "^2.0.0-beta.10","@aws-sdk/client-s3": "^3.850.0","@paralleldrive/cuid2": "^2.2.2",@@ -50,7 +50,7 @@"@tailwindcss/typography": "^0.5.12","@upstash/redis": "^1.34.0","@vercel/analytics": "^1.5.0",- "ai": "^5.0.0-beta.25",+ "ai": "5.0.0-beta.29","class-variance-authority": "^0.7.1","clsx": "^2.1.0","cmdk": "1.0.0",