Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 04:45 UTC
| 1 | /** |
| 2 | * Vercel AI Provider |
| 3 | * To be used with the Vercel AI SDK |
| 4 | * |
| 5 | * Author: Musthaq Ahamad <musthaq@composio.dev> |
| 6 | * Legacy Reference: https://github.com/ComposioHQ/composio/blob/master/js/src/frameworks/vercel.ts |
| 7 | * |
| 8 | * This provider provides a set of tools for interacting with Vercel AI SDK. |
| 9 | * |
| 10 | * @packageDocumentation |
| 11 | * @module providers/vercel |
| 12 | */ |
| 13 | import { |
| 14 | BaseAgenticProvider, |
| 15 | Tool, |
| 16 | ExecuteToolFn, |
| 17 | McpUrlResponse, |
| 18 | McpServerGetResponse, |
| 19 | deduplicateJsonSchemaRequiredArrays, |
| 20 | dereferenceJsonSchema, |
| 21 | toStrictJsonSchema, |
| 22 | jsonSchemaToZodSchema, |
| 23 | logger, |
| 24 | normalizeToolArguments, |
| 25 | omitNullToolArguments, |
| 26 | } from '@composio/core'; |
| 27 | import type { ToolSet as VercelToolSet, Tool as VercelTool } from 'ai'; |
| 28 | import { jsonSchema, tool } from 'ai'; |
| 29 | |
| 30 | type AiJsonSchema = Parameters<typeof jsonSchema>[0]; |
| 31 | |
| 32 | /** |
| 33 | * The AI SDK schema for a tool input: the model is shown `schema` itself, and |
| 34 | * tool-call arguments are validated with the Zod schema built from it. |
| 35 | */ |
| 36 | const toolInputSchema = (schema: Record<string, unknown>) => { |
| 37 | const validator = jsonSchemaToZodSchema(schema); |
| 38 | return jsonSchema(schema as AiJsonSchema, { |
| 39 | validate: async value => { |
| 40 | const result = await validator.safeParseAsync(value); |
| 41 | return result.success |
| 42 | ? { success: true, value: result.data } |
| 43 | : { success: false, error: result.error }; |
| 44 | }, |
| 45 | }); |
| 46 | }; |
| 47 | |
| 48 | export type VercelToolCollection = VercelToolSet; |
| 49 | export class VercelProvider extends BaseAgenticProvider< |
| 50 | VercelToolCollection, |
| 51 | VercelTool, |
| 52 | McpServerGetResponse |
| 53 | > { |
| 54 | readonly name = 'vercel'; |
| 55 | private strict: boolean | null; |
| 56 | /** |
| 57 | * Creates a new instance of the VercelProvider. |
| 58 | * |
| 59 | * This provider enables integration with the Vercel AI SDK, |
| 60 | * allowing Composio tools to be used with Vercel AI applications. |
| 61 | * |
| 62 | * @example |
| 63 | * ```typescript |
| 64 | * // Initialize the Vercel provider |
| 65 | * const provider = new VercelProvider(); |
| 66 | * |
| 67 | * // Use with Composio |
| 68 | * const composio = new Composio({ |
| 69 | * apiKey: 'your-api-key', |
| 70 | * provider: new VercelProvider() |
| 71 | * }); |
| 72 | * |
| 73 | * // Use the provider to wrap tools for Vercel AI SDK |
| 74 | * const vercelTools = provider.wrapTools(composioTools, composio.tools.execute); |
| 75 | * ``` |
| 76 | * |
| 77 | * @param options.strict - Rewrites each tool's input schema into the form |
| 78 | * OpenAI strict mode accepts, and validates tool-call arguments against it. |
| 79 | * It does not set the AI SDK's per-tool `strict` flag, so the model provider |
| 80 | * does not enforce the schema. Anthropic strict mode rejects requests with |
| 81 | * typical sets of rewritten tools; see the README. |
| 82 | */ |
| 83 | constructor({ strict = false }: { strict?: boolean } = {}) { |
| 84 | super(); |
| 85 | this.strict = strict; |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Wraps a Composio tool in a Vercel AI SDK tool format. |
| 90 | * |
| 91 | * This method transforms a Composio tool definition into the format |
| 92 | * expected by Vercel's AI SDK for function calling. |
| 93 | * |
| 94 | * @param {ComposioTool} composioTool - The Composio tool to wrap |
| 95 | * @param {ExecuteToolFn} executeTool - Function to execute the tool |
| 96 | * @returns {VercelTool} The wrapped Vercel tool |
| 97 | * |
| 98 | * @example |
| 99 | * ```typescript |
| 100 | * // Wrap a single tool for use with Vercel AI SDK |
| 101 | * const composioTool = { |
| 102 | * slug: 'SEARCH_TOOL', |
| 103 | * description: 'Search for information', |
| 104 | * inputParameters: { |
| 105 | * type: 'object', |
| 106 | * properties: { |
| 107 | * query: { type: 'string' } |
| 108 | * }, |
| 109 | * required: ['query'] |
| 110 | * } |
| 111 | * }; |
| 112 | * |
| 113 | * // Create a Vercel tool using the provider |
| 114 | * const vercelTool = provider.wrapTool( |
| 115 | * composioTool, |
| 116 | * composio.tools.execute |
| 117 | * ); |
| 118 | * |
| 119 | * // Use with Vercel AI SDK |
| 120 | * import { StreamingTextResponse, Message } from 'ai'; |
| 121 | * import { OpenAI } from 'openai'; |
| 122 | * |
| 123 | * export async function POST(req: Request) { |
| 124 | * const { messages } = await req.json(); |
| 125 | * const openai = new OpenAI(); |
| 126 | * |
| 127 | * const response = await openai.chat.completions.create({ |
| 128 | * model: 'gpt-4', |
| 129 | * messages, |
| 130 | * tools: [vercelTool] |
| 131 | * }); |
| 132 | * |
| 133 | * return new StreamingTextResponse(response.choices[0].message); |
| 134 | * } |
| 135 | * ``` |
| 136 | */ |
| 137 | wrapTool(composioTool: Tool, executeTool: ExecuteToolFn): VercelTool { |
| 138 | const inputParams = composioTool.inputParameters; |
| 139 | |
| 140 | // Canonicalize required arrays at the vendor-schema emission boundary. |
| 141 | let parameters: Record<string, unknown> = deduplicateJsonSchemaRequiredArrays( |
| 142 | (inputParams ?? {}) as Record<string, unknown> |
| 143 | ); |
| 144 | // Under strict mode optional parameters are emitted as required-nullable, |
| 145 | // so a `null` the tool's own schema does not accept means "omitted". |
| 146 | let strictSource: Record<string, unknown> | undefined; |
| 147 | if (this.strict && inputParams) { |
| 148 | // Structured outputs enforce their contract at every depth: all |
| 149 | // properties required, closed objects, no annotation keywords. The |
| 150 | // strict rewrite keeps every parameter (optional ones become nullable) |
| 151 | // and reports constructs it cannot express; such a tool keeps its |
| 152 | // original schema rather than a narrower one. |
| 153 | const strict = toStrictJsonSchema(inputParams); |
| 154 | if (strict.unsupported.length > 0) { |
| 155 | const reasons = strict.unsupported |
| 156 | .map(entry => `${entry.path || '<root>'}: ${entry.keyword} (${entry.detail})`) |
| 157 | .join('; '); |
| 158 | logger.warn( |
| 159 | `VercelProvider: tool "${composioTool.slug}" keeps its non-strict schema because it cannot be expressed as strict structured outputs: ${reasons}` |
| 160 | ); |
| 161 | } else { |
| 162 | if (strict.totalChanges > 0) { |
| 163 | logger.debug( |
| 164 | `VercelProvider: strict mode rewrote ${strict.totalChanges} node(s) of tool "${composioTool.slug}": ${strict.changes |
| 165 | .map(change => `${change.path}: ${change.reason}`) |
| 166 | .join('; ')}` |
| 167 | ); |
| 168 | } |
| 169 | parameters = strict.schema; |
| 170 | strictSource = strict.source; |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // The model sees the tool's JSON Schema as is, so keywords a Zod schema |
| 175 | // cannot carry (`format`, `contentEncoding`, `contentMediaType`, `title`, |
| 176 | // ...) reach it. The Zod converter does not follow $ref, so inline the |
| 177 | // definitions first (cycles fall back to the permissive sentinel). |
| 178 | const inputSchema = toolInputSchema( |
| 179 | dereferenceJsonSchema(parameters, { onUnresolved: 'sentinel' }) |
| 180 | ); |
| 181 | |
| 182 | return tool({ |
| 183 | description: composioTool.description, |
| 184 | inputSchema, |
| 185 | |
| 186 | execute: async params => { |
| 187 | // Models occasionally emit tool input as a JSON string rather than an object (issue #2406). |
| 188 | const normalized = normalizeToolArguments(params, composioTool.slug); |
| 189 | return await executeTool( |
| 190 | composioTool.slug, |
| 191 | strictSource ? omitNullToolArguments(normalized, strictSource) : normalized |
| 192 | ); |
| 193 | }, |
| 194 | }); |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * Wraps a list of Composio tools as a Vercel AI SDK tool collection. |
| 199 | * |
| 200 | * This method transforms multiple Composio tool definitions into the format |
| 201 | * expected by Vercel's AI SDK for function calling, organizing them |
| 202 | * into a dictionary keyed by tool slug. |
| 203 | * |
| 204 | * @param {ComposioTool[]} tools - Array of Composio tools to wrap |
| 205 | * @param {ExecuteToolFn} executeTool - Function to execute the tools |
| 206 | * @returns {VercelToolCollection} Dictionary of wrapped tools in Vercel AI SDK format |
| 207 | * |
| 208 | * @example |
| 209 | * ```typescript |
| 210 | * // Wrap multiple tools for use with Vercel AI SDK |
| 211 | * const composioTools = [ |
| 212 | * { |
| 213 | * slug: 'SEARCH_TOOL', |
| 214 | * description: 'Search for information', |
| 215 | * inputParameters: { |
| 216 | * type: 'object', |
| 217 | * properties: { |
| 218 | * query: { type: 'string' } |
| 219 | * }, |
| 220 | * required: ['query'] |
| 221 | * } |
| 222 | * }, |
| 223 | * { |
| 224 | * slug: 'WEATHER_TOOL', |
| 225 | * description: 'Get weather information', |
| 226 | * inputParameters: { |
| 227 | * type: 'object', |
| 228 | * properties: { |
| 229 | * location: { type: 'string' } |
| 230 | * }, |
| 231 | * required: ['location'] |
| 232 | * } |
| 233 | * } |
| 234 | * ]; |
| 235 | * |
| 236 | * // Create Vercel tools using the provider |
| 237 | * const vercelTools = provider.wrapTools( |
| 238 | * composioTools, |
| 239 | * composio.tools.execute |
| 240 | * ); |
| 241 | * |
| 242 | * // Use with Vercel AI SDK in a Next.js API route |
| 243 | * import { StreamingTextResponse } from 'ai'; |
| 244 | * import { OpenAI } from 'openai'; |
| 245 | * |
| 246 | * export async function POST(req: Request) { |
| 247 | * const { messages } = await req.json(); |
| 248 | * const openai = new OpenAI(); |
| 249 | * |
| 250 | * const response = await openai.chat.completions.create({ |
| 251 | * model: 'gpt-4', |
| 252 | * messages, |
| 253 | * tools: Object.values(vercelTools) |
| 254 | * }); |
| 255 | * |
| 256 | * return new StreamingTextResponse(response.choices[0].message); |
| 257 | * } |
| 258 | * ``` |
| 259 | */ |
| 260 | wrapTools(tools: Tool[], executeTool: ExecuteToolFn): VercelToolCollection { |
| 261 | return tools.reduce((acc, tool) => { |
| 262 | acc[tool.slug] = this.wrapTool(tool, executeTool); |
| 263 | return acc; |
| 264 | }, {} as VercelToolCollection); |
| 265 | } |
| 266 | |
| 267 | /** |
| 268 | * Transform an MCP URL response into the Vercel provider's format. |
| 269 | * Vercel uses the standard MCP server response shape, mapping each |
| 270 | * entry to an object with a `URL` instance and its name. |
| 271 | * |
| 272 | * @param data - The MCP URL response data |
| 273 | * @returns Standard MCP server response format |
| 274 | */ |
| 275 | wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse { |
| 276 | // Vercel uses the standard format |
| 277 | return data.map(item => ({ |
| 278 | url: new URL(item.url), |
| 279 | name: item.name, |
| 280 | })) as McpServerGetResponse; |
| 281 | } |
| 282 | } |