@auto-engineer/ai-gateway 0.1.1

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/dist/index.js ADDED
@@ -0,0 +1,351 @@
1
+ import { generateText, streamText, generateObject, streamObject } from 'ai';
2
+ import { openai } from '@ai-sdk/openai';
3
+ import { anthropic } from '@ai-sdk/anthropic';
4
+ import { google } from '@ai-sdk/google';
5
+ import { xai } from '@ai-sdk/xai';
6
+ import { configureAIProvider } from './config.js';
7
+ import { z } from 'zod';
8
+ import { getRegisteredToolsForAI } from './mcp-server.js';
9
+ import { startServer } from './mcp-server.js';
10
+ export var AIProvider;
11
+ (function (AIProvider) {
12
+ AIProvider["OpenAI"] = "openai";
13
+ AIProvider["Anthropic"] = "anthropic";
14
+ AIProvider["Google"] = "google";
15
+ AIProvider["XAI"] = "xai";
16
+ })(AIProvider || (AIProvider = {}));
17
+ const defaultOptions = {
18
+ temperature: 0.7,
19
+ maxTokens: 1000,
20
+ };
21
+ function getDefaultModel(provider) {
22
+ switch (provider) {
23
+ case AIProvider.OpenAI:
24
+ return 'gpt-4o-mini';
25
+ case AIProvider.Anthropic:
26
+ return 'claude-sonnet-4-20250514';
27
+ case AIProvider.Google:
28
+ return 'gemini-2.5-pro';
29
+ case AIProvider.XAI:
30
+ return 'grok-3';
31
+ default:
32
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
33
+ throw new Error(`Unknown provider: ${provider}`);
34
+ }
35
+ }
36
+ function getModel(provider, model) {
37
+ const modelName = model ?? getDefaultModel(provider);
38
+ switch (provider) {
39
+ case AIProvider.OpenAI:
40
+ return openai(modelName);
41
+ case AIProvider.Anthropic:
42
+ return anthropic(modelName);
43
+ case AIProvider.Google:
44
+ return google(modelName);
45
+ case AIProvider.XAI:
46
+ return xai(modelName);
47
+ default:
48
+ throw new Error(`Unknown provider: ${provider}`);
49
+ }
50
+ }
51
+ export async function generateTextWithAI(prompt, provider, options = {}) {
52
+ const finalOptions = { ...defaultOptions, ...options };
53
+ const model = finalOptions.model ?? getDefaultModel(provider);
54
+ const modelInstance = getModel(provider, model);
55
+ if (finalOptions.includeTools === true) {
56
+ await startServer();
57
+ const result = await generateTextWithToolsAI(prompt, provider, options);
58
+ return result.text;
59
+ }
60
+ const result = await generateText({
61
+ model: modelInstance,
62
+ prompt,
63
+ temperature: finalOptions.temperature,
64
+ maxTokens: finalOptions.maxTokens,
65
+ });
66
+ return result.text;
67
+ }
68
+ export async function* streamTextWithAI(prompt, provider, options = {}) {
69
+ const finalOptions = { ...defaultOptions, ...options };
70
+ const model = getModel(provider, finalOptions.model);
71
+ const stream = await streamText({
72
+ model,
73
+ prompt,
74
+ temperature: finalOptions.temperature,
75
+ maxTokens: finalOptions.maxTokens,
76
+ });
77
+ for await (const chunk of stream.textStream) {
78
+ yield chunk;
79
+ }
80
+ }
81
+ /**
82
+ * Generates text using streaming and collects the full response.
83
+ * Optionally calls a stream callback for each token if provided.
84
+ * Always returns the complete collected response.
85
+ */
86
+ export async function generateTextStreamingWithAI(prompt, provider, options = {}) {
87
+ const finalOptions = { ...defaultOptions, ...options };
88
+ let collectedResult = '';
89
+ const stream = streamTextWithAI(prompt, provider, finalOptions);
90
+ for await (const token of stream) {
91
+ // Collect all tokens for the final result
92
+ collectedResult += token;
93
+ // Call the stream callback if provided
94
+ if (finalOptions.streamCallback) {
95
+ finalOptions.streamCallback(token);
96
+ }
97
+ }
98
+ return collectedResult;
99
+ }
100
+ export async function generateTextWithToolsAI(prompt, provider, options = {}) {
101
+ const finalOptions = { ...defaultOptions, ...options };
102
+ const model = finalOptions.model ?? getDefaultModel(provider);
103
+ const modelInstance = getModel(provider, model);
104
+ const registeredTools = finalOptions.includeTools === true ? getRegisteredToolsForAI() : {};
105
+ console.log('registeredTools', registeredTools);
106
+ const hasTools = Object.keys(registeredTools).length > 0;
107
+ console.log('hasTools', hasTools);
108
+ // Build conversation messages
109
+ const messages = [{ role: 'user', content: prompt }];
110
+ let finalResult = '';
111
+ const allToolCalls = [];
112
+ let attempts = 0;
113
+ const maxAttempts = 5;
114
+ while (attempts < maxAttempts) {
115
+ attempts++;
116
+ const opts = {
117
+ model: modelInstance,
118
+ messages,
119
+ temperature: finalOptions.temperature,
120
+ maxTokens: finalOptions.maxTokens,
121
+ ...(hasTools && {
122
+ tools: registeredTools,
123
+ toolChoice: 'auto',
124
+ }),
125
+ };
126
+ console.log('opts', opts);
127
+ const result = await generateText(opts);
128
+ console.log('result', JSON.stringify(result, null, 2));
129
+ // Add assistant message to conversation
130
+ if (result.text) {
131
+ messages.push({ role: 'assistant', content: result.text });
132
+ finalResult = result.text;
133
+ }
134
+ // If there are tool calls, execute them and continue conversation
135
+ if (result.toolCalls !== undefined && result.toolCalls.length > 0) {
136
+ allToolCalls.push(...result.toolCalls);
137
+ // Execute tools and create a simple follow-up prompt
138
+ const toolResults = await executeToolCalls(result.toolCalls, registeredTools);
139
+ // Add the tool results as a user message and request a final response
140
+ messages.push({
141
+ role: 'user',
142
+ content: `${toolResults}Based on this product catalog data, please provide specific product recommendations for a soccer-loving daughter. Include product names, prices, and reasons why each item would be suitable.`,
143
+ });
144
+ // Continue the conversation to get AI's response to tool results
145
+ continue;
146
+ }
147
+ // If no tool calls, we're done
148
+ break;
149
+ }
150
+ return {
151
+ text: finalResult,
152
+ toolCalls: allToolCalls,
153
+ };
154
+ }
155
+ async function executeToolCalls(toolCalls, registeredTools) {
156
+ let toolResults = '';
157
+ for (const toolCall of toolCalls) {
158
+ try {
159
+ const toolCallObj = toolCall;
160
+ const tool = registeredTools[toolCallObj.toolName];
161
+ if (tool?.execute) {
162
+ const toolResult = await tool.execute(toolCallObj.args);
163
+ toolResults += `Tool ${toolCallObj.toolName} returned: ${String(toolResult)}\n\n`;
164
+ }
165
+ else {
166
+ toolResults += `Error: Tool ${toolCallObj.toolName} not found or missing execute function\n\n`;
167
+ }
168
+ }
169
+ catch (error) {
170
+ const toolCallObj = toolCall;
171
+ console.error(`Tool execution error for ${toolCallObj.toolName}:`, error);
172
+ toolResults += `Error executing tool ${toolCallObj.toolName}: ${String(error)}\n\n`;
173
+ }
174
+ }
175
+ return toolResults;
176
+ }
177
+ export async function generateTextWithImageAI(text, imageBase64, provider, options = {}) {
178
+ const finalOptions = { ...defaultOptions, ...options };
179
+ const model = finalOptions.model ?? getDefaultModel(provider);
180
+ const modelInstance = getModel(provider, model);
181
+ if (provider !== AIProvider.OpenAI && provider !== AIProvider.XAI) {
182
+ throw new Error(`Provider ${provider} does not support image inputs`);
183
+ }
184
+ const result = await generateText({
185
+ model: modelInstance,
186
+ messages: [
187
+ {
188
+ role: 'user',
189
+ content: [
190
+ { type: 'text', text },
191
+ { type: 'image', image: imageBase64 },
192
+ ],
193
+ },
194
+ ],
195
+ temperature: finalOptions.temperature,
196
+ maxTokens: finalOptions.maxTokens,
197
+ });
198
+ return result.text;
199
+ }
200
+ export function getAvailableProviders() {
201
+ const config = configureAIProvider();
202
+ const providers = [];
203
+ if (config.openai != null)
204
+ providers.push(AIProvider.OpenAI);
205
+ if (config.anthropic != null)
206
+ providers.push(AIProvider.Anthropic);
207
+ if (config.google != null)
208
+ providers.push(AIProvider.Google);
209
+ if (config.xai != null)
210
+ providers.push(AIProvider.XAI);
211
+ return providers;
212
+ }
213
+ function getEnhancedPrompt(prompt, lastError) {
214
+ const errorDetails = lastError.zodIssues
215
+ ? JSON.stringify(lastError.zodIssues, null, 2)
216
+ : lastError.validationDetails?.cause?.issues
217
+ ? JSON.stringify(lastError.validationDetails.cause.issues, null, 2)
218
+ : lastError.message;
219
+ return `${prompt}\\n\\n⚠️ IMPORTANT: Your previous response failed validation with the following errors:\\n${errorDetails}\\n\\nPlease fix these errors and ensure your response EXACTLY matches the required schema structure.`;
220
+ }
221
+ function isSchemaError(error) {
222
+ return (error.message.includes('response did not match schema') ||
223
+ error.message.includes('TypeValidationError') ||
224
+ error.name === 'AI_TypeValidationError');
225
+ }
226
+ function enhanceValidationError(error) {
227
+ const enhancedError = new Error(error.message);
228
+ Object.assign(enhancedError, error);
229
+ if (error.cause !== undefined || error.issues !== undefined || error.errors !== undefined) {
230
+ enhancedError.validationDetails = {
231
+ cause: error.cause,
232
+ issues: error.issues,
233
+ errors: error.errors,
234
+ };
235
+ }
236
+ if (error.message.includes('response did not match schema') &&
237
+ 'cause' in error &&
238
+ typeof error.cause === 'object' &&
239
+ error.cause !== null &&
240
+ 'issues' in error.cause) {
241
+ enhancedError.zodIssues = error.cause.issues;
242
+ }
243
+ return enhancedError;
244
+ }
245
+ function handleFailedRequest(lastError, maxRetries, attempt) {
246
+ if (!lastError || !isSchemaError(lastError) || attempt >= maxRetries - 1) {
247
+ return { shouldRetry: false, enhancedError: lastError };
248
+ }
249
+ console.log(`Schema validation failed on attempt ${attempt + 1}/${maxRetries}, retrying...`);
250
+ const enhancedError = enhanceValidationError(lastError);
251
+ return { shouldRetry: true, enhancedError };
252
+ }
253
+ export async function generateStructuredDataWithAI(prompt, provider, options) {
254
+ const maxSchemaRetries = 3;
255
+ let lastError;
256
+ if (options.includeTools === true)
257
+ await startServer();
258
+ const registeredTools = options.includeTools === true ? getRegisteredToolsForAI() : {};
259
+ console.log('registeredTools', registeredTools);
260
+ const hasTools = Object.keys(registeredTools).length > 0;
261
+ console.log('hasTools', hasTools);
262
+ for (let attempt = 0; attempt < maxSchemaRetries; attempt++) {
263
+ try {
264
+ const model = getModel(provider, options.model);
265
+ const enhancedPrompt = attempt > 0 && lastError ? getEnhancedPrompt(prompt, lastError) : prompt;
266
+ console.log('enhancedPrompt', enhancedPrompt);
267
+ const opts = {
268
+ model,
269
+ prompt: enhancedPrompt,
270
+ schema: options.schema,
271
+ schemaName: options.schemaName,
272
+ schemaDescription: options.schemaDescription,
273
+ temperature: options.temperature,
274
+ maxTokens: options.maxTokens,
275
+ ...(hasTools && {
276
+ tools: registeredTools,
277
+ toolChoice: 'auto',
278
+ }),
279
+ };
280
+ console.log('opts', opts);
281
+ const result = await generateObject(opts);
282
+ console.log('result', JSON.stringify(result, null, 2));
283
+ return result.object;
284
+ }
285
+ catch (error) {
286
+ lastError =
287
+ error instanceof Error
288
+ ? error
289
+ : new Error('An unknown error occurred');
290
+ const { shouldRetry, enhancedError } = handleFailedRequest(lastError, maxSchemaRetries, attempt);
291
+ lastError = enhancedError;
292
+ if (!shouldRetry) {
293
+ throw lastError;
294
+ }
295
+ }
296
+ }
297
+ // If we exhausted all retries, throw the last error
298
+ throw lastError;
299
+ }
300
+ export async function streamStructuredDataWithAI(prompt, provider, options) {
301
+ const maxSchemaRetries = 3;
302
+ let lastError;
303
+ for (let attempt = 0; attempt < maxSchemaRetries; attempt++) {
304
+ try {
305
+ const model = getModel(provider, options.model);
306
+ const enhancedPrompt = attempt > 0 && lastError ? getEnhancedPrompt(prompt, lastError) : prompt;
307
+ const result = streamObject({
308
+ model,
309
+ prompt: enhancedPrompt,
310
+ schema: options.schema,
311
+ schemaName: options.schemaName,
312
+ schemaDescription: options.schemaDescription,
313
+ temperature: options.temperature,
314
+ maxTokens: options.maxTokens,
315
+ });
316
+ // Stream partial objects if callback provided
317
+ if (options.onPartialObject) {
318
+ void (async () => {
319
+ try {
320
+ for await (const partialObject of result.partialObjectStream) {
321
+ options.onPartialObject?.(partialObject);
322
+ }
323
+ }
324
+ catch (streamError) {
325
+ console.error('Error in partial object stream:', streamError);
326
+ }
327
+ })();
328
+ }
329
+ // Return the final complete object
330
+ return await result.object;
331
+ }
332
+ catch (error) {
333
+ lastError =
334
+ error instanceof Error
335
+ ? error
336
+ : new Error('An unknown error occurred');
337
+ const { shouldRetry, enhancedError } = handleFailedRequest(lastError, maxSchemaRetries, attempt);
338
+ lastError = enhancedError;
339
+ if (!shouldRetry) {
340
+ throw lastError;
341
+ }
342
+ }
343
+ }
344
+ // If we exhausted all retries, throw the last error
345
+ throw lastError;
346
+ }
347
+ // Export zod for convenience
348
+ export { z };
349
+ // Export MCP server singleton functions
350
+ export { server as mcpServer, registerTool, registerTools, startServer, isServerStarted, getRegisteredTools, getRegisteredToolsForAI, getToolHandler, getSchemaByName, executeRegisteredTool, } from './mcp-server.js';
351
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC5E,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAqB3C,MAAM,CAAN,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,+BAAiB,CAAA;IACjB,qCAAuB,CAAA;IACvB,+BAAiB,CAAA;IACjB,yBAAW,CAAA;AACb,CAAC,EALW,UAAU,KAAV,UAAU,QAKrB;AAoBD,MAAM,cAAc,GAAc;IAChC,WAAW,EAAE,GAAG;IAChB,SAAS,EAAE,IAAI;CAChB,CAAC;AAEF,SAAS,eAAe,CAAC,QAAoB;IAC3C,QAAQ,QAAQ,EAAE,CAAC;QACjB,KAAK,UAAU,CAAC,MAAM;YACpB,OAAO,aAAa,CAAC;QACvB,KAAK,UAAU,CAAC,SAAS;YACvB,OAAO,0BAA0B,CAAC;QACpC,KAAK,UAAU,CAAC,MAAM;YACpB,OAAO,gBAAgB,CAAC;QAC1B,KAAK,UAAU,CAAC,GAAG;YACjB,OAAO,QAAQ,CAAC;QAClB;YACE,4EAA4E;YAC5E,MAAM,IAAI,KAAK,CAAC,qBA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A2B,CAAC;YAExE,MAAM,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,mBAAmB,CAAC,SAAS,EAAE,gBAAgB,EAAE,OAAO,CAAC,CAAC;YACjG,SAAS,GAAG,aAAa,CAAC;YAE1B,IAAI,CAAC,WAAW,EAAE,CAAC;gBACjB,MAAM,SAAS,CAAC;YAClB,CAAC;QACH,CAAC;IACH,CAAC;IAED,oDAAoD;IACpD,MAAM,SAAS,CAAC;AAClB,CAAC;AAED,6BAA6B;AAC7B,OAAO,EAAE,CAAC,EAAE,CAAC;AAEb,wCAAwC;AACxC,OAAO,EACL,MAAM,IAAI,SAAS,EACnB,YAAY,EACZ,aAAa,EACb,WAAW,EACX,eAAe,EACf,kBAAkB,EAClB,uBAAuB,EACvB,cAAc,EACd,eAAe,EACf,qBAAqB,GAGtB,MAAM,cAAc,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.specs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.specs.d.ts","sourceRoot":"","sources":["../src/index.specs.ts"],"names":[],"mappings":""}
@@ -0,0 +1,14 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { generateTextWithAI, streamTextWithAI, AIProvider } from './index.js';
3
+ describe('AI Integration', () => {
4
+ process.env.OPENAI_API_KEY = 'test';
5
+ it('should export the correct types', () => {
6
+ expect(typeof generateTextWithAI).toBe('function');
7
+ expect(typeof streamTextWithAI).toBe('function');
8
+ });
9
+ it('should have valid AIProvider type', () => {
10
+ const providers = [AIProvider.OpenAI, AIProvider.Anthropic, AIProvider.Google, AIProvider.XAI];
11
+ expect(providers).toContain(AIProvider.OpenAI);
12
+ });
13
+ });
14
+ //# sourceMappingURL=index.specs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.specs.js","sourceRoot":"","sources":["../src/index.specs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE3E,QAAQ,CAAC,gBAAgB,EAAE,GAAG,EAAE;IAC9B,OAAO,CAAC,GAAG,CAAC,cAAc,GAAG,MAAM,CAAC;IAEpC,EAAE,CAAC,iCAAiC,EAAE,GAAG,EAAE;QACzC,MAAM,CAAC,OAAO,kBAAkB,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACnD,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACnD,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,mCAAmC,EAAE,GAAG,EAAE;QAC3C,MAAM,SAAS,GAAiB,CAAC,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,SAAS,EAAE,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC;QAC7G,MAAM,CAAC,SAAS,CAAC,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACjD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,50 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { z } from 'zod';
3
+ interface ToolResult {
4
+ content: Array<{
5
+ type: 'text';
6
+ text: string;
7
+ }>;
8
+ isError?: boolean;
9
+ [key: string]: unknown;
10
+ }
11
+ interface ToolDescription {
12
+ title: string;
13
+ description: string;
14
+ inputSchema: Record<string, z.ZodSchema>;
15
+ schema?: z.ZodSchema;
16
+ schemaName?: string;
17
+ schemaDescription?: string;
18
+ }
19
+ type ToolHandler<T extends Record<string, unknown> = Record<string, unknown>> = (params: T) => Promise<ToolResult>;
20
+ interface RegisteredTool {
21
+ name: string;
22
+ description: ToolDescription;
23
+ handler: ToolHandler<Record<string, unknown>>;
24
+ aiSdkTool: {
25
+ parameters: z.ZodSchema;
26
+ description: string;
27
+ execute?: (args: Record<string, unknown>) => Promise<string>;
28
+ };
29
+ }
30
+ declare const server: McpServer;
31
+ export { server };
32
+ export declare function registerTool<T extends Record<string, unknown> = Record<string, unknown>>(name: string, description: ToolDescription, handler: ToolHandler<T>): void;
33
+ export declare function registerTools<T extends Record<string, unknown> = Record<string, unknown>>(tools: Array<{
34
+ name: string;
35
+ description: ToolDescription;
36
+ handler: ToolHandler<T>;
37
+ }>): void;
38
+ export declare function startServer(): Promise<void>;
39
+ export declare function isServerStarted(): boolean;
40
+ export declare function getRegisteredTools(): RegisteredTool[];
41
+ export declare function getRegisteredToolsForAI(): Record<string, {
42
+ parameters: z.ZodSchema;
43
+ description: string;
44
+ execute?: (args: Record<string, unknown>) => Promise<string>;
45
+ }>;
46
+ export declare function getToolHandler(name: string): ToolHandler | undefined;
47
+ export declare function executeRegisteredTool(name: string, params: Record<string, unknown>): Promise<ToolResult>;
48
+ export declare function getSchemaByName(schemaName: string): z.ZodSchema | undefined;
49
+ export type { ToolResult, ToolDescription, ToolHandler, RegisteredTool };
50
+ //# sourceMappingURL=mcp-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-server.d.ts","sourceRoot":"","sources":["../src/mcp-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAEpE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,UAAU,UAAU;IAClB,OAAO,EAAE,KAAK,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,CAAC,CAAC;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,UAAU,eAAe;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC;IACz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B,CAAC,QAQH;AAED,wBAAsB,WAAW,kBAKhC;AAED,wBAAgB,eAAe,YAE9B;AAED,wBAAgB,kBAAkB,IAAI,cAAc,EAAE,CAErD;AAED,wBAAgB,uBAAuB,IAAI,MAAM,CAC/C,MAAM,EACN;IACE,UAAU,EAAE,CAAC,CAAC,SAAS,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9D,CACF,CAgBA;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAEpE;AAED,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,CAM9G;AAED,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,CAAC,CAAC,SAAS,GAAG,SAAS,CAQ3E;AAED,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,WAAW,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1,121 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { z } from 'zod';
4
+ const server = new McpServer({
5
+ name: 'frontend-implementation',
6
+ version: '0.1.0',
7
+ });
8
+ const transport = new StdioServerTransport();
9
+ let isStarted = false;
10
+ const toolRegistry = new Map();
11
+ async function cleanup() {
12
+ console.log('Cleaning up...');
13
+ await transport.close();
14
+ process.exit(0);
15
+ }
16
+ process.on('SIGTERM', () => {
17
+ void cleanup();
18
+ });
19
+ process.on('SIGINT', () => {
20
+ void cleanup();
21
+ });
22
+ export { server };
23
+ function createMcpHandler(handler) {
24
+ return (args, _extra) => {
25
+ return handler(args);
26
+ };
27
+ }
28
+ function createAiSdkTool(description, handler) {
29
+ const parameterSchema = Object.keys(description.inputSchema).length > 0 ? z.object(description.inputSchema) : z.object({}).passthrough();
30
+ return {
31
+ parameters: parameterSchema,
32
+ description: description.description,
33
+ execute: async (args) => {
34
+ const result = await handler(args);
35
+ const textOutput = result.content[0]?.text || '';
36
+ // If a schema is provided, parse and validate the JSON output
37
+ if (description.schema) {
38
+ try {
39
+ const parsed = JSON.parse(textOutput);
40
+ description.schema.parse(parsed);
41
+ return textOutput; // Return original text output for consistency
42
+ }
43
+ catch (parseError) {
44
+ console.warn(`Tool failed to parse/validate JSON output:`, parseError);
45
+ return textOutput; // Fallback to raw text
46
+ }
47
+ }
48
+ return textOutput;
49
+ },
50
+ ...(description.schema && { schema: description.schema }),
51
+ ...(description.schemaName != null && { schemaName: description.schemaName }),
52
+ ...(description.schemaDescription != null && { schemaDescription: description.schemaDescription }),
53
+ };
54
+ }
55
+ export function registerTool(name, description, handler) {
56
+ console.log(`🔧 Registering MCP tool: ${name}`);
57
+ if (isStarted) {
58
+ throw new Error('Cannot register tools after server has started');
59
+ }
60
+ const mcpHandler = createMcpHandler(handler);
61
+ const aiSdkTool = createAiSdkTool(description, handler);
62
+ const registeredTool = {
63
+ name,
64
+ description,
65
+ handler: handler,
66
+ aiSdkTool,
67
+ };
68
+ toolRegistry.set(name, registeredTool);
69
+ server.registerTool(name, description, mcpHandler);
70
+ console.log(`✅ Tool ${name} registered successfully. Total tools: ${toolRegistry.size}`);
71
+ }
72
+ export function registerTools(tools) {
73
+ if (isStarted) {
74
+ throw new Error('Cannot register tools after server has started');
75
+ }
76
+ tools.forEach((tool) => {
77
+ registerTool(tool.name, tool.description, tool.handler);
78
+ });
79
+ }
80
+ export async function startServer() {
81
+ if (isStarted)
82
+ return;
83
+ await server.connect(transport);
84
+ isStarted = true;
85
+ }
86
+ export function isServerStarted() {
87
+ return isStarted;
88
+ }
89
+ export function getRegisteredTools() {
90
+ return Array.from(toolRegistry.values());
91
+ }
92
+ export function getRegisteredToolsForAI() {
93
+ console.log(`📋 Getting registered tools for AI. Registry size: ${toolRegistry.size}`);
94
+ const tools = {};
95
+ for (const tool of toolRegistry.values()) {
96
+ tools[tool.name] = tool.aiSdkTool;
97
+ console.log(` - Tool: ${tool.name}`);
98
+ }
99
+ console.log(`📊 Returning ${Object.keys(tools).length} tools for AI`);
100
+ return tools;
101
+ }
102
+ export function getToolHandler(name) {
103
+ return toolRegistry.get(name)?.handler;
104
+ }
105
+ export async function executeRegisteredTool(name, params) {
106
+ const tool = toolRegistry.get(name);
107
+ if (!tool) {
108
+ throw new Error(`Tool '${name}' not found`);
109
+ }
110
+ return await tool.handler(params);
111
+ }
112
+ export function getSchemaByName(schemaName) {
113
+ console.log();
114
+ for (const tool of toolRegistry.values()) {
115
+ if (tool.description?.schemaName === schemaName) {
116
+ return tool.description.schema;
117
+ }
118
+ }
119
+ return undefined;
120
+ }
121
+ //# sourceMappingURL=mcp-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-server.js","sourceRoot":"","sources":["../src/mcp-server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAiCxB,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IAC3B,IAAI,EAAE,yBAAyB;IAC/B,OAAO,EAAE,OAAO;CACjB,CAAC,CAAC;AAEH,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAE7C,IAAI,SAAS,GAAG,KAAK,CAAC;AACtB,MAAM,YAAY,GAAG,IAAI,GAAG,EAA0B,CAAC;AAEvD,KAAK,UAAU,OAAO;IACpB,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC9B,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;IACxB,OAAO,CAAC,IAAI,CAAC,CA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zC,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,IAAY,EAAE,MAA+B;IACvF,MAAM,IAAI,GAAG,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,SAAS,IAAI,aAAa,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,UAAkB;IAChD,OAAO,CAAC,GAAG,EAAE,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,YAAY,CAAC,MAAM,EAAE,EAAE,CAAC;QACzC,IAAI,IAAI,CAAC,WAAW,EAAE,UAAU,KAAK,UAAU,EAAE,CAAC;YAChD,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;QACjC,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@auto-engineer/ai-gateway",
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ }
12
+ },
13
+ "scripts": {
14
+ "build": "tsc && tsx ../../scripts/fix-esm-imports.ts",
15
+ "dev": "tsc --watch",
16
+ "test": "vitest run",
17
+ "lint": "eslint 'src/**/*.ts' --max-warnings 0 --config ../../eslint.config.ts",
18
+ "lint:fix": "eslint 'src/**/*.ts' --fix --config ../../eslint.config.ts",
19
+ "type-check": "tsc --noEmit",
20
+ "format": "prettier --write \"**/*.{js,ts,json,md,yml,yaml}\" --ignore-path ../../.prettierignore",
21
+ "format:fix": "prettier --write \"**/*.{js,ts,json,md,yml,yaml}\" --ignore-path ../../.prettierignore",
22
+ "link:dev": "pnpm build && pnpm link --global",
23
+ "unlink:dev": "pnpm unlink --global"
24
+ },
25
+ "dependencies": {
26
+ "@ai-sdk/anthropic": "^1.2.12",
27
+ "@ai-sdk/google": "^1.2.19",
28
+ "@ai-sdk/openai": "^1.3.22",
29
+ "@ai-sdk/xai": "^1.2.16",
30
+ "@modelcontextprotocol/sdk": "^1.3.0",
31
+ "ai": "^4.3.16",
32
+ "dotenv": "^16.4.5",
33
+ "zod": "^3.25.67"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ }
38
+ }
package/src/config.ts ADDED
@@ -0,0 +1,39 @@
1
+ import dotenv from 'dotenv';
2
+ import { fileURLToPath } from 'url';
3
+ import { dirname, resolve } from 'path';
4
+ const __filename = fileURLToPath(import.meta.url);
5
+ const __dirname = dirname(__filename);
6
+ dotenv.config({ path: resolve(__dirname, '../../../.env') });
7
+
8
+ export interface AIConfig {
9
+ openai?: {
10
+ apiKey: string;
11
+ };
12
+ anthropic?: {
13
+ apiKey: string;
14
+ };
15
+ google?: {
16
+ apiKey: string;
17
+ };
18
+ xai?: {
19
+ apiKey: string;
20
+ };
21
+ }
22
+
23
+ export function configureAIProvider(): AIConfig {
24
+ const config = {
25
+ openai: process.env.OPENAI_API_KEY != null ? { apiKey: process.env.OPENAI_API_KEY } : undefined,
26
+ anthropic: process.env.ANTHROPIC_API_KEY != null ? { apiKey: process.env.ANTHROPIC_API_KEY } : undefined,
27
+ google:
28
+ process.env.GOOGLE_GENERATIVE_AI_API_KEY != null
29
+ ? { apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY }
30
+ : undefined,
31
+ xai: process.env.XAI_API_KEY != null ? { apiKey: process.env.XAI_API_KEY } : undefined,
32
+ };
33
+ if (config.openai == null && config.anthropic == null && config.google == null && config.xai == null) {
34
+ throw new Error(
35
+ 'At least one AI provider must be configured. Please set OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, or XAI_API_KEY environment variables.',
36
+ );
37
+ }
38
+ return config;
39
+ }