|
| 1 | +import { openai } from "@ai-sdk/openai"; |
| 2 | +import { CoreMessage, experimental_createMCPClient, generateText } from "ai"; |
| 3 | +import { |
| 4 | + createBaseProgram, |
| 5 | + validateAndParseOptions, |
| 6 | + createMCPTransport, |
| 7 | + logProcessingStart, |
| 8 | + logStep, |
| 9 | + logToolsLoading, |
| 10 | + logAvailableTools, |
| 11 | + logAIResponse, |
| 12 | + logResponse, |
| 13 | + logToolCalls, |
| 14 | + logToolResults, |
| 15 | + logConversationComplete, |
| 16 | + logMaxStepsReached, |
| 17 | + logSessionComplete, |
| 18 | + logClosingClient, |
| 19 | + logClientClosed, |
| 20 | + logContinuing, |
| 21 | + setupGracefulShutdown, |
| 22 | + handleError, |
| 23 | + SYSTEM_PROMPT, |
| 24 | + ProgramOptions, |
| 25 | +} from "../shared/cli.js"; |
| 26 | + |
| 27 | +const program = createBaseProgram( |
| 28 | + "ai-sdk", |
| 29 | + "AI SDK CLI tool with MCP integration" |
| 30 | +); |
| 31 | + |
| 32 | +program.action(async (instruction: string, options: ProgramOptions) => { |
| 33 | + const config = validateAndParseOptions(instruction, options); |
| 34 | + |
| 35 | + let mcpClient: |
| 36 | + | Awaited<ReturnType<typeof experimental_createMCPClient>> |
| 37 | + | undefined; |
| 38 | + |
| 39 | + try { |
| 40 | + logProcessingStart(config, "AI SDK"); |
| 41 | + |
| 42 | + const transport = await createMCPTransport(config.options.external_user_id); |
| 43 | + |
| 44 | + // Initialize the MCP client from AI SDK |
| 45 | + mcpClient = await experimental_createMCPClient({ |
| 46 | + transport, |
| 47 | + }); |
| 48 | + |
| 49 | + console.log("✅ MCP client initialized"); |
| 50 | + |
| 51 | + const messages: CoreMessage[] = [ |
| 52 | + { |
| 53 | + role: "system", |
| 54 | + content: SYSTEM_PROMPT, |
| 55 | + }, |
| 56 | + { |
| 57 | + role: "user", |
| 58 | + content: config.instruction, |
| 59 | + }, |
| 60 | + ]; |
| 61 | + |
| 62 | + let ended = false; |
| 63 | + let steps = 0; |
| 64 | + |
| 65 | + // Main conversation loop - continues until AI decides to stop or max steps reached |
| 66 | + while (!ended && steps < config.maxSteps) { |
| 67 | + logStep(steps + 1, config.maxSteps); |
| 68 | + |
| 69 | + // Reload tools from MCP client before each generation step |
| 70 | + // This ensures we have the latest available tools (servers can add/remove tools dynamically) |
| 71 | + logToolsLoading(); |
| 72 | + const tools = await mcpClient.tools(); |
| 73 | + const toolNames = Object.keys(tools).join(", "); |
| 74 | + logAvailableTools(toolNames); |
| 75 | + |
| 76 | + logAIResponse(); |
| 77 | + |
| 78 | + // Generate response with AI SDK - key configuration: |
| 79 | + // - tools: Makes MCP tools available to the model |
| 80 | + // - maxSteps: 1 ensures we handle one step at a time for better control |
| 81 | + const response = await generateText({ |
| 82 | + model: openai(config.options.model as any), |
| 83 | + messages, |
| 84 | + tools, |
| 85 | + maxSteps: 1, // Handle one step at a time so we are able to reload the tools in between steps |
| 86 | + }); |
| 87 | + |
| 88 | + logResponse(response.text); |
| 89 | + |
| 90 | + // Handle different completion reasons - this determines conversation flow |
| 91 | + switch (response.finishReason) { |
| 92 | + case "stop": |
| 93 | + case "content-filter": |
| 94 | + // Model completed its response naturally or was filtered |
| 95 | + ended = true; |
| 96 | + logConversationComplete(); |
| 97 | + break; |
| 98 | + |
| 99 | + case "error": |
| 100 | + // An error occurred during generation |
| 101 | + ended = true; |
| 102 | + console.error("❌ An error occurred during generation"); |
| 103 | + break; |
| 104 | + |
| 105 | + case "tool-calls": |
| 106 | + // Model wants to use tools |
| 107 | + // AI SDK automatically executes the tools and provides results |
| 108 | + logToolCalls(); |
| 109 | + response.toolCalls.forEach((toolCall, index) => { |
| 110 | + console.log(` ${index + 1}. ${toolCall.toolName}`); |
| 111 | + console.log( |
| 112 | + ` Args: ${JSON.stringify(toolCall.args, null, 2)}` |
| 113 | + ); |
| 114 | + }); |
| 115 | + |
| 116 | + logToolResults(); |
| 117 | + response.toolResults.forEach((result, index) => { |
| 118 | + console.log(` ${index + 1}. ${JSON.stringify(result, null, 2)}`); |
| 119 | + }); |
| 120 | + |
| 121 | + // Add the tool calls and results to conversation history |
| 122 | + messages.push( |
| 123 | + { |
| 124 | + role: "assistant", |
| 125 | + content: response.toolCalls, |
| 126 | + }, |
| 127 | + { |
| 128 | + role: "tool", |
| 129 | + content: response.toolResults, |
| 130 | + } |
| 131 | + ); |
| 132 | + break; |
| 133 | + |
| 134 | + case "length": |
| 135 | + console.log("⚠️ Response truncated due to length limit"); |
| 136 | + ended = true; |
| 137 | + break; |
| 138 | + |
| 139 | + default: |
| 140 | + console.log(`🤔 Unknown finish reason: ${response.finishReason}`); |
| 141 | + ended = true; |
| 142 | + } |
| 143 | + |
| 144 | + steps++; |
| 145 | + |
| 146 | + if (!ended && steps < config.maxSteps) { |
| 147 | + logContinuing(); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + if (steps >= config.maxSteps) { |
| 152 | + logMaxStepsReached(config.maxSteps); |
| 153 | + } |
| 154 | + |
| 155 | + logSessionComplete(); |
| 156 | + } catch (error) { |
| 157 | + handleError(error, "AI SDK"); |
| 158 | + } finally { |
| 159 | + if (mcpClient) { |
| 160 | + logClosingClient(); |
| 161 | + await mcpClient.close(); |
| 162 | + logClientClosed(); |
| 163 | + } |
| 164 | + } |
| 165 | +}); |
| 166 | + |
| 167 | +setupGracefulShutdown(); |
| 168 | + |
| 169 | +program.parse(); |
0 commit comments