MCPcopy Index your code
hub / github.com/TanStack/ai / wrapCode

Function wrapCode

packages/ai-isolate-cloudflare/src/worker/wrap-code.ts:126–197  ·  view source on GitHub ↗
(
  code: string,
  tools: Array<ToolSchema>,
  toolResults?: Record<string, ToolResultPayload>,
)

Source from the content-addressed store, hash-verified

124 * Wrap user code in an async IIFE with tool wrappers
125 */
126export function wrapCode(
127 code: string,
128 tools: Array<ToolSchema>,
129 toolResults?: Record<string, ToolResultPayload>,
130): string {
131 const toolWrappers = generateToolWrappers(tools, toolResults)
132 const toolResultsJson = toolResults ? JSON.stringify(toolResults) : '{}'
133
134 return `
135 (async function() {
136 // Tool call tracking (sequential index for stable IDs across re-executions)
137 let __toolCallIdx = 0;
138 const __pendingToolCalls = [];
139 const __toolResults = ${toolResultsJson};
140 const __logs = [];
141
142 // Special error class for tool calls
143 class __ToolCallNeeded extends Error {
144 constructor(callId) {
145 super('Tool call needed: ' + callId);
146 this.callId = callId;
147 }
148 }
149
150 // Console capture
151 const console = {
152 log: (...args) => __logs.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
153 error: (...args) => __logs.push('ERROR: ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
154 warn: (...args) => __logs.push('WARN: ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
155 info: (...args) => __logs.push('INFO: ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
156 };
157
158 // Tool wrappers
159 ${toolWrappers}
160
161 try {
162 // Execute user code
163 const __userResult = await (async function() {
164 ${code}
165 })();
166
167 return {
168 status: 'done',
169 success: true,
170 value: __userResult,
171 logs: __logs
172 };
173 } catch (__error) {
174 if (__error instanceof __ToolCallNeeded) {
175 // Tool calls needed - return pending calls
176 return {
177 status: 'need_tools',
178 toolCalls: __pendingToolCalls,
179 logs: __logs
180 };
181 }
182
183 // Regular error

Callers 3

executeCodeFunction · 0.90
worker.test.tsFile · 0.90

Calls 1

generateToolWrappersFunction · 0.85

Tested by

no test coverage detected