Update agent with new Gemini SDK and MCP integration

This commit is contained in:
josedario87
2025-06-05 00:51:05 -06:00
parent e6caa03987
commit 7d0495eff6
4 changed files with 913 additions and 16 deletions

View File

@@ -1,5 +1,7 @@
import express from 'express';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { GoogleGenAI, mcpToTool } from '@google/genai';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import dotenv from 'dotenv';
dotenv.config();
@@ -8,9 +10,20 @@ const PORT = Number(process.env.PORT) || 8001;
const API_KEY = process.env.GEMINI_API_KEY || '';
console.log(`Using Gemini API key: ${API_KEY}`);
const genAI = API_KEY ? new GoogleGenerativeAI(API_KEY) : null;
const model = genAI ? genAI.getGenerativeModel({ model: 'gemini-pro' }) : null;
const genAI = API_KEY ? new GoogleGenAI({ apiKey: API_KEY }) : null;
const MCP_URL = process.env.MCP_URL || 'http://planilla.interno.mcp';
let mcpClient: Client | undefined;
let mcpTransport: StreamableHTTPClientTransport | undefined;
async function getMcpClient(): Promise<Client> {
if (!mcpClient) {
mcpClient = new Client({ name: 'planilla-client', version: '1.0.0' });
mcpTransport = new StreamableHTTPClientTransport(new URL(MCP_URL));
await mcpClient.connect(mcpTransport);
}
return mcpClient;
}
const repoInfo = `This repository contains a WhatsApp router, a simple chat UI and now a conversation-layer-agent service.
- whatsapp-router: Forwards WhatsApp messages to configured agents.
- chat-ui: Minimal web interface that also talks to an agent.
@@ -24,14 +37,23 @@ app.post('/', async (req, res) => {
const message = req.body?.message as string | undefined;
if (!message) return res.status(400).json({ error: 'Missing message' });
if (!model) {
if (!genAI) {
return res.json({ reply: repoInfo });
}
try {
const prompt = `Repo information: ${repoInfo}\nUser message: ${message}`;
const result = await model.generateContent(prompt);
const reply = result.response.text().trim();
const contents = `Repo information: ${repoInfo}\nUser message: ${message}`;
const config: any = {};
if (message.toLowerCase().includes('/planilla')) {
const client = await getMcpClient();
config.tools = [mcpToTool(client)];
}
const result = await genAI.models.generateContent({
model: 'gemini-2.0-flash',
contents,
config,
});
const reply = (result.text || '').trim();
res.json({ reply });
} catch (err: any) {
console.error('Gemini error', err.message);