实战 新增 Agent、新增页面、新增 MCP 工具、导航配置、API Route 开发
新增 Agent 是最常见的开发任务,必须完成以下 3 个步骤(第 2 步最容易忘记!):
在 src/agents/ 目录下创建 Agent 文件,使用 defineAgent 辅助函数:
// src/agents/my-new-agent.js
import { defineAgent } from '@/lib/agents/define';
import { createReactAgent } from '@langchain/langgraph/prebuilt';
import { ChatOpenAI } from '@langchain/openai';
import { MODEL_CONFIG } from '@/config/modelConfig';
import { getMCPTools, getGitCloneTools } from '@/agents/tools';
export default defineAgent({
// === 元数据 ===
id: 'my-new-agent', // 可选,默认从文件名推断
name: '我的新助手',
description: '这个 Agent 做什么...',
isPublic: true, // 是否在前端列表中显示
// === UI 布局 ===
requiresDrawio: false, // 需要 DrawIO 编辑器分屏?
requiresXmind: false, // 需要 XMind 脑图分屏?
allowAddKnowledge: false, // 允许添加知识库?
// === 示例问题 ===
examples: [
{ key: 'ex1', icon: 'BulbOutlined', label: '示例问题 1' },
{ key: 'ex2', icon: 'CodeOutlined', label: '示例问题 2' },
],
// === Agent 创建函数 ===
createAgent: async (options = {}) => {
const { formData = {} } = options;
const model = new ChatOpenAI({
model: MODEL_CONFIG.defaultModel,
temperature: 0.3,
apiKey: MODEL_CONFIG.defaultApiKey,
configuration: { baseURL: MODEL_CONFIG.defaultBaseHost },
});
// 并行加载工具
const [mcpTools, gitTools] = await Promise.all([
getMCPTools({
my_server: {
transport: 'http',
url: 'https://kuai-mcp.example.com/groups/xxx/mcp',
},
}, { agentName: 'MyNewAgent' }),
getGitCloneTools(),
]);
return createReactAgent({
llm: model,
tools: [...mcpTools, ...gitTools],
});
},
});
由于 Next.js 的动态导入限制,所有 Agent 必须手动在 scanner.js 中注册:
// src/lib/agents/scanner.js
// 1. 添加 import
import myNewAgent from '@/agents/my-new-agent';
// 2. 在 AGENT_MODULES 数组中添加
const AGENT_MODULES = [
// ... 现有 agents
{ filename: 'my-new-agent.js', module: myNewAgent }, // ← 新增这一行
];
# 1. 启动开发服务器
pnpm dev
# 2. 检查控制台日志,应看到:
# [AgentScanner] Registered agent: my-new-agent (我的新助手)
# 3. 验证 API 返回
curl http://localhost:3000/api/agents | grep "my-new-agent"
# 4. 在浏览器中访问测试
# http://localhost:3000/agents?agent=my-new-agent
| 配置项 | 类型 | 说明 |
|---|---|---|
id | string | Agent ID(可选,默认从文件名推断) |
name | string | 显示名称(必填) |
description | string | 描述(必填) |
isPublic | boolean | 是否在前端列表显示 |
requiresDrawio | boolean | 启用 DrawIO 编辑器分屏布局 |
requiresXmind | boolean | 启用 XMind 脑图分屏布局 |
allowAddKnowledge | boolean | 启用知识库导入功能 |
initialForm | object | 对话前收集信息的表单配置 |
examples | Array | 示例问题列表 |
createAgent | Function | 创建 LangGraph Agent 的函数(必填) |
项目使用 Next.js 16 App Router 的文件系统路由,新增页面只需在 src/app/ 下创建对应文件。
src/app/
├── my-feature/
│ ├── page.js # 页面组件(必需)
│ ├── layout.js # 可选:页面布局
│ ├── loading.js # 可选:加载状态
│ └── error.js # 可选:错误处理
// src/app/my-feature/page.js
'use client'; // 如需使用 hooks
import { useSelector } from 'react-redux';
import { MyComponent } from '@/components/features/my-feature';
export default function MyFeaturePage() {
// 获取 Redux 状态
const { data } = useSelector(state => state.config);
return (
<div>
<h1>我的功能</h1>
<MyComponent data={data} />
</div>
);
}
| 类型 | 目录 | 说明 |
|---|---|---|
| 功能组件 | src/components/features/[功能名]/ | 业务相关的组件 |
| 通用组件 | src/components/common/ | 可复用的基础组件 |
| 布局组件 | src/components/layout/ | Header、Footer、Sider 等 |
如果需要让 Agent 使用新的 MCP 工具,有两种方式:
只需在 Agent 的 createAgent 中配置 MCP 服务器 URL,工具会自动加载:
const tools = await getMCPTools({
my_server: {
transport: 'http',
url: 'https://kuai-mcp.example.com/groups/my-group/mcp',
},
}, {
agentName: 'MyAgent',
// 可选:只暴露部分工具
includeTools: ['tool_a', 'tool_b'],
// 可选:排除某些工具
excludeTools: ['dangerous_tool'],
// 可选:覆盖冗长描述
descriptionOverrides: {
tool_a: '更简洁的描述',
},
});
如果需要添加非 MCP 的自定义工具,使用 LangChain 的 tool() 函数:
import { tool } from '@langchain/core/tools';
import { z } from 'zod';
const myCustomTool = tool(
async (input) => {
// 工具逻辑
const { param1, param2 } = input;
const result = await doSomething(param1, param2);
return JSON.stringify(result);
},
{
name: 'my_custom_tool',
description: '工具描述,告诉 Agent 什么时候使用这个工具',
schema: z.object({
param1: z.string().describe('参数1的描述'),
param2: z.number().optional().describe('参数2的描述(可选)'),
}),
}
);
// 在 createAgent 中使用
return createReactAgent({
llm: model,
tools: [...mcpTools, myCustomTool],
});
如果工具需要在多个 Agent 中复用,在 src/agents/tools/ 创建独立文件并从 index.js 导出:
// src/agents/tools/myTools.js
import { tool } from '@langchain/core/tools';
import { z } from 'zod';
export function createMyTool(options = {}) {
return tool(async (input) => { /* ... */ }, {
name: 'my_tool',
description: '...',
schema: z.object({ /* ... */ }),
});
}
export function getMyTools() {
return [createMyTool()];
}
// src/agents/tools/index.js — 添加导出
export { createMyTool, getMyTools } from './myTools';
侧边栏导航在 src/config/navigation.js 中集中管理。新增页面后,需要在这里添加对应的导航项。
// src/config/navigation.js
export const navbarMenu = [
{
label: '工作台',
key: 'dashboard',
icon: <HomeOutlined />,
path: '/dashboard',
},
{
label: 'Agent管理',
key: 'application',
icon: <AppstoreOutlined />,
children: [
{ label: 'Agent列表', key: 'app-list', path: '/application/list' },
{ label: '会话历史', key: 'chat-history', path: '/application/chat-history' },
],
},
{
label: 'MCP管理',
key: 'mcp',
icon: <ApiOutlined />,
children: [
{ label: 'MCP服务器', key: 'mcp-servers', path: '/mcp/servers' },
],
},
// ... 更多导航项
];
// 示例:添加"我的功能"导航项
{
label: '我的功能',
key: 'my-feature',
icon: <ToolOutlined />,
path: '/my-feature',
},
// 或者作为子菜单
{
label: '工具箱',
key: 'toolbox',
icon: <ToolOutlined />,
children: [
{ label: '我的功能', key: 'my-feature', path: '/my-feature' },
{ label: '另一个功能', key: 'another', path: '/another' },
],
},
key 必须全局唯一,不能与其他导航项重复。path 必须与 src/app/ 下的文件系统路由匹配。
项目使用 Next.js API Routes 实现服务端逻辑,并通过 rewrites 代理后端请求。新增 API Route 有两个必须步骤。
// src/app/api/my-feature/route.js
import { NextResponse } from 'next/server';
export async function GET(request) {
// 处理 GET 请求
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');
return NextResponse.json({ data: { id, name: 'test' } });
}
export async function POST(request) {
// 处理 POST 请求
const body = await request.json();
// ... 业务逻辑
return NextResponse.json({ success: true });
}
在 next.config.js 的 rewrites 数组前面添加排除规则:
// next.config.js
async rewrites() {
return [
// ✅ 新增:排除新的 API Route(放在最前面!)
{
source: '/api/my-feature/:path*',
destination: '/api/my-feature/:path*',
},
// 现有排除规则
{ source: '/api/agents/:path*', destination: '/api/agents/:path*' },
{ source: '/api/health/:path*', destination: '/api/health/:path*' },
// ...
// ⚠️ 通用代理规则(必须放在最后!)
{
source: '/api/:path*',
destination: 'http://backend.com/api/:path*',
},
];
}
/api/my-feature/* 会被最后的通用规则 /api/:path* 代理到后端,导致本地 API Route 不生效。
src/app/api/[feature]/route.js 创建文件next.config.js 的 rewrites 数组前面添加排除规则NextResponse 返回响应(不是 res.json())| 路径 | 说明 |
|---|---|
/api/agents/* | Agent 元数据和对话 API |
/api/health/* | 健康检查 |
/api/share/* | 分享功能 |
/api/chat-history/* | 聊天历史 |
/api/proxy/* | 代理请求 |
/api/agui/* | AG-UI 协议 |
/api/metrics/* | 指标监控 |
/api/ai/* | AI 相关 API |
src/app/ 创建路由文件src/config/navigation.js 添加配置src/components/features/ 组织组件src/services/modules/ 添加 API 服务src/agents/ 创建 Agent 文件src/lib/agents/scanner.js 中添加/agents?agent=my-agent 测试src/agents/skills/ 创建目录(kebab-case)references/ 添加最佳实践和示例getSkillTools({ skills: ['my-skill'] })| 问题 | 原因 | 解决方案 |
|---|---|---|
| Agent 不显示 | 未在 scanner.js 注册 | 添加 import 和 AGENT_MODULES 条目 |
| API 被代理到后端 | 缺少 rewrites 排除规则 | 在 rewrites 数组前面添加排除规则 |
| Module not found: stream | LangChain 需要 Node.js polyfill | 在 turbopack.resolveAlias 中配置 |
| MCP 工具加载失败 | MCP 服务不可达或 CORS 问题 | 验证 URL、检查 CORS 配置 |
| Redux 状态刷新丢失 | 数据仅在内存中 | 使用 localStorage 或 redux-persist |
| ClaudeCode 连接失败 | CLI/SDK 不可用或配置错误 | 检查模型、API Key、workDir 配置 |
AGENT_MODULES 数组中注册,否则不会出现在 Agent 列表中。/api/:path* 后面,新 Route 会被通用规则代理到后端,导致本地 API Route 不生效。必须放在前面。requiresRedux 不是 defineAgent 的有效配置项。有效的配置包括 requiresDrawio(DrawIO 分屏)、requiresXmind(XMind 分屏)、allowAddKnowledge(知识库导入)等。Redux 是全局状态管理,与 Agent 定义无关。