🤖 MCP Agent-具有模型上下文协议的AI助手
使用Next.js构建的强大AI聊天机器人应用程序,利用模型上下文协议(MCP)通过自定义工具、资源和提示扩展LLM功能。此代理可以与外部API交互,执行自定义函数,并通过多步工具执行提供增强的响应。
✨ 特性
🎯 核心能力
- 多模型支持:在OpenAI、Groq和Google Gemini模型之间切换
- MCP工具集成:使用模型上下文协议的可扩展工具系统
- 多步推理:AI可以按顺序执行多个工具来完成复杂的任务
- 实时聊天界面:具有markdown渲染的现代响应式聊天用户界面
- 会话管理:保存、加载和管理多个聊天对话
- 工具调用可视化:实时查看AI正在使用哪些工具
🛠️ 内置工具
- GitHub仓库获取器:查询GitHub用户存储库的详细信息
- 时间工具:获取当前时间和日期信息
- 问候工具:用于自定义实现的简单示例工具
🎨 UI/UX功能
- 明暗主题:在克劳德风格的灯光模式和时尚的黑暗模式之间切换
- Markdown支持:带有语法高亮显示的完整markdown渲染
- 快速模板:常见任务的预构建提示
- 消息操作:复制邮件,重新生成响应
- 响应式设计:在桌面和移动设备上无缝工作
🏗️ 技术栈
前端
- Next.js 16.1 -带有App Router的React框架
- 反应19.2 -使用React编译器的UI库
- TypeScript 5 -类型安全开发
- 顺风CSS 4 -实用性优先的造型
- Radix UI -可访问的组件图元
人工智能和后端
- Vercel AI SDK -LLM交互的统一接口
- XMCP -模型上下文协议实现
- @ai sdk/mcp -用于AI SDK的MCP适配器
- 萨德 -工具的模式验证
支持的LLM提供商
- OpenAI(GPT-4、GPT-3.5)
- 格罗克(混合,火焰)
- 谷歌(Gemini Pro)
📋 先决条件
在开始之前,请确保您已经:
- Node.js 20.x或更高
- npm 或 纱线 包管理器
- 至少一个LLM提供程序的API密钥:
- OpenAI API密钥 - Groq API密钥 - 谷歌人工智能API密钥
🚀 入门指南
1.克隆存储库
git clone https://github.com/Jdrao7/ai-agent-mcptools.git
cd mcp-agent2.安装依赖项
npm install
# or
yarn install3.环境配置
创建 .env.local 根目录中的文件:
# Choose your preferred LLM provider(s)
OPENAI_API_KEY=sk-your-openai-key-here
GROQ_API_KEY=gsk_your-groq-key-here
GOOGLE_GENERATIVE_AI_API_KEY=your-gemini-key-here
# Optional: Configure other settings
NEXT_PUBLIC_APP_URL=http://localhost:30004.启动开发服务器
npm run dev该应用程序将在 http://localhost:3000
📂 项目结构
mcp-agent/
├── src/
│ ├── app/ # Next.js App Router
│ │ ├── page.tsx # Landing page
│ │ ├── chat/ # Chat interface
│ │ │ └── page.tsx # Main chat UI
│ │ ├── actions/ # Server actions
│ │ │ └── chat.ts # Chat action handler
│ │ └── api/ # API routes
│ │ ├── chat/ # Chat API endpoint
│ │ └── mcp/ # MCP server endpoint
│ ├── components/ # React components
│ │ ├── MarkdownRenderer.tsx # Markdown display
│ │ ├── ToolCallsDisplay.tsx # Tool execution viewer
│ │ └── ui/ # Reusable UI components
│ ├── orchestrator/ # AI orchestration logic
│ │ ├── llm_orchestrator.ts # Multi-step tool execution
│ │ └── MCPClient.ts # MCP client initialization
│ ├── lib/ # Utility libraries
│ │ └── model/ # LLM provider configs
│ │ ├── openai.ts
│ │ ├── groq.ts
│ │ └── gemini.ts
│ ├── tools/ # MCP Tools (auto-discovered)
│ │ ├── github.ts # GitHub API tool
│ │ ├── time.ts # Time utilities
│ │ └── greet.ts # Example tool
│ ├── prompts/ # MCP Prompts
│ │ └── review-code.ts # Code review prompt
│ └── resources/ # MCP Resources
│ ├── (config)/
│ │ └── app.ts # App configuration
│ └── (users)/
│ └── [userId]/
│ └── profile.ts # User profiles
├── public/ # Static assets
├── xmcp.config.ts # XMCP configuration
├── next.config.ts # Next.js configuration
└── package.json # Dependencies🔧 配置
XMCP配置(xmcp.config.ts)
import { type XmcpConfig } from "xmcp";
const config: XmcpConfig = {
http: true, // Enable HTTP server
experimental: {
adapter: "nextjs", // Use Next.js adapter
},
paths: {
tools: "src/tools", // Tools directory
prompts: "src/prompts", # Prompts directory
resources: "src/resources", // Resources directory
},
};
export default config;切换LLM模型
编辑 src/orchestrator/llm_orchestrator.ts 要更改模型,请执行以下操作:
// Option 1: Use Groq (default)
import { getGroqModel } from '@/lib/model/groq';
const model = getGroqModel();
// Option 2: Use OpenAI
import { getOpenAIModel } from '@/lib/model/openai';
const model = getOpenAIModel();
// Option 3: Use Gemini
import { getGeminiModel } from '@/lib/model/gemini';
const model = getGeminiModel();🛠️ 创建自定义工具
工具是MCP Agent的核心扩展机制。以下是如何创建自己的:
示例:天气工具
创建 src/tools/weather.ts:
import { z } from "zod";
import { type InferSchema } from "xmcp";
// Define input schema
export const schema = {
city: z.string().describe("The city name to get weather for"),
units: z.enum(["celsius", "fahrenheit"]).optional().describe("Temperature units"),
};
// Define tool metadata
export const metadata = {
name: "get_weather",
description: "Get current weather information for a city",
annotations: {
title: "Weather Information",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: false,
},
};
// Implement tool logic
export default async function getWeather({
city,
units = "celsius"
}: InferSchema) {
try {
// Your API call here
const response = await fetch(
`https://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q=${city}`
);
const data = await response.json();
return {
content: [{
type: "text",
text: `Weather in ${city}: ${data.current.temp_c}°C, ${data.current.condition.text}`
}],
};
} catch (error) {
return {
content: [{
type: "text",
text: `Failed to fetch weather: ${error.message}`
}],
isError: true,
};
}
}工具最佳实践
- 清晰的描述:编写工具和参数的详细说明
- 错误处理:始终包含try-catch块并返回有意义的错误
- 类型安全:使用Zod模式进行运行时验证
- 注释:适当地将工具标记为只读、破坏性或幂等
- 测试:在与AI集成之前独立测试工具
💬 用法
基本聊天
- 导航到
/chat - 在输入框中键入您的消息
- 按Enter键或单击发送
- 观看人工智能使用工具来增强其响应
查询示例
"Show me the GitHub repositories for user Jdrao7"
→ Uses github tool to fetch repository data
"What time is it?"
→ Uses time tool to get current time
"Analyze this code and suggest improvements"
→ May use multiple tools in sequence多步工具执行
代理最多可以执行5轮工具调用来完成复杂的任务:
User: "Find my latest GitHub repo and tell me what time it was created"
Step 1: Calls get_github_repos tool
Step 2: Analyzes repo data
Step 3: Calls time tool for timezone conversion
Step 4: Synthesizes final response🧪 发展
可用脚本
# Start development server (XMCP + Next.js)
npm run dev
# Build for production
npm run build
# Start production server
npm start
# Run linter
npm run lint开发技巧
- 热重载:XMCP会自动检测工具的更改
- 调试:检查浏览器控制台和终端以获取详细日志
- 工具测试:集成前单独测试工具
- 模型选择:针对不同用例尝试不同的模型
添加新资源
资源为AI提供静态或动态数据 src/resources/:
// src/resources/docs/api.ts
export const metadata = {
name: "api-documentation",
mimeType: "text/plain",
};
export default async function getApiDocs() {
return {
contents: [{
text: "Your API documentation here...",
mimeType: "text/plain",
}],
};
}📦 生产大楼
# Build the application
npm run build
# Start production server
npm start部署选项
Vercel(推荐)
# Install Vercel CLI
npm i -g vercel
# Deploy
vercel码头工人
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["npm", "start"]环境变量
确保在部署平台中设置了所有必需的环境变量:
OPENAI_API_KEY/GROQ_API_KEY/GOOGLE_GENERATIVE_AI_API_KEYNEXT_PUBLIC_APP_URL(您部署的URL)
🤝 贡献
欢迎投稿!以下是如何做出贡献:
- 分叉存储库
- 创建要素分支:
git checkout -b feature/amazing-feature - 提交您的更改:
git commit -m 'Add amazing feature' - 推到分支:
git push origin feature/amazing-feature - 打开拉取请求
贡献理念
- 添加新的MCP工具(例如,数据库查询、文件操作)
- 改进UI/UX
- 添加更多LLM提供程序集成
- 编写文档和教程
- 报告错误并建议功能
📄 许可证
该项目是开源的,可在 MIT许可证.
🙏 致谢
- Vercel AI SDK -人工智能框架
- XMCP -MCP实施
- 模型上下文协议 -工具规格
- Next.js -React框架
- 安thropic克劳德 -UI灵感
📬 联系
由...创建: @Jdrao7
项目链接:
______________________________________________________________________
Made with ❤️ and ☕
