🚀 kuai-service-front 开发实战指南

实战 新增 Agent、新增页面、新增 MCP 工具、导航配置、API Route 开发

🤖 1. 如何新增 Agent(3 步)

新增 Agent 是最常见的开发任务,必须完成以下 3 个步骤(第 2 步最容易忘记!):

步骤 1:创建 Agent 定义文件

在 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],
    });
  },
});

步骤 2:在 scanner.js 中注册 ⚠️ 必须!

由于 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 },  // ← 新增这一行
];
最常见的错误:忘记在 scanner.js 中注册!Agent 文件写好了但不出现在列表中,99% 是因为漏了这一步。

步骤 3:验证

# 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

defineAgent 配置速查

配置项类型说明
idstringAgent ID(可选,默认从文件名推断)
namestring显示名称(必填)
descriptionstring描述(必填)
isPublicboolean是否在前端列表显示
requiresDrawioboolean启用 DrawIO 编辑器分屏布局
requiresXmindboolean启用 XMind 脑图分屏布局
allowAddKnowledgeboolean启用知识库导入功能
initialFormobject对话前收集信息的表单配置
examplesArray示例问题列表
createAgentFunction创建 LangGraph Agent 的函数(必填)

📄 2. 如何新增页面

项目使用 Next.js 16 App Router 的文件系统路由,新增页面只需在 src/app/ 下创建对应文件。

2.1 创建页面文件

src/app/
├── my-feature/
│   ├── page.js           # 页面组件(必需)
│   ├── layout.js         # 可选:页面布局
│   ├── loading.js        # 可选:加载状态
│   └── error.js          # 可选:错误处理

2.2 页面组件模板

// 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>
  );
}

2.3 组件组织规范

类型目录说明
功能组件src/components/features/[功能名]/业务相关的组件
通用组件src/components/common/可复用的基础组件
布局组件src/components/layout/Header、Footer、Sider 等

🔧 3. 如何新增 MCP 工具

如果需要让 Agent 使用新的 MCP 工具,有两种方式:

3.1 使用已有 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: '更简洁的描述',
  },
});

3.2 使用自定义工具(非 MCP)

如果需要添加非 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],
});

3.3 注册为可复用工具

如果工具需要在多个 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';

🧭 4. 导航配置

侧边栏导航在 src/config/navigation.js 中集中管理。新增页面后,需要在这里添加对应的导航项。

4.1 导航配置结构

// 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' },
    ],
  },
  // ... 更多导航项
];

4.2 添加新导航项

// 示例:添加"我的功能"导航项
{
  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/ 下的文件系统路由匹配。

🔌 5. API Route 开发

项目使用 Next.js API Routes 实现服务端逻辑,并通过 rewrites 代理后端请求。新增 API Route 有两个必须步骤。

5.1 创建 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 });
}

5.2 添加 rewrites 排除规则 ⚠️ 必须!

在 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*',
    },
  ];
}
为什么需要排除规则?Next.js 的 rewrites 按顺序匹配。如果没有排除规则,/api/my-feature/* 会被最后的通用规则 /api/:path* 代理到后端,导致本地 API Route 不生效。

5.3 API Route 开发检查清单

5.4 现有 API Routes 一览

路径说明
/api/agents/*Agent 元数据和对话 API
/api/health/*健康检查
/api/share/*分享功能
/api/chat-history/*聊天历史
/api/proxy/*代理请求
/api/agui/*AG-UI 协议
/api/metrics/*指标监控
/api/ai/*AI 相关 API

📋 6. 开发流程总结

6.1 新功能开发流程

  1. 创建页面:在 src/app/ 创建路由文件
  2. 添加导航:在 src/config/navigation.js 添加配置
  3. 创建组件:在 src/components/features/ 组织组件
  4. API 集成:在 src/services/modules/ 添加 API 服务
  5. 状态管理:复杂状态用 Redux,简单状态用 React hooks

6.2 Agent 开发流程

  1. 定义 Agent:在 src/agents/ 创建 Agent 文件
  2. 注册 Agent:在 src/lib/agents/scanner.js 中添加
  3. 测试 Agent:访问 /agents?agent=my-agent 测试
  4. 集成工具:MCP / ClaudeCode / Git Clone / XMind / DrawIO
  5. 优化提示词:调整系统提示词和技能描述

6.3 技能开发流程

  1. 创建技能目录:在 src/agents/skills/ 创建目录(kebab-case)
  2. 编写 SKILL.md:包含 YAML frontmatter(name + description)
  3. 添加参考资料:在 references/ 添加最佳实践和示例
  4. 测试技能:在 Agent 中使用 getSkillTools({ skills: ['my-skill'] })

🐛 7. 常见问题速查

问题原因解决方案
Agent 不显示未在 scanner.js 注册添加 import 和 AGENT_MODULES 条目
API 被代理到后端缺少 rewrites 排除规则在 rewrites 数组前面添加排除规则
Module not found: streamLangChain 需要 Node.js polyfill在 turbopack.resolveAlias 中配置
MCP 工具加载失败MCP 服务不可达或 CORS 问题验证 URL、检查 CORS 配置
Redux 状态刷新丢失数据仅在内存中使用 localStorage 或 redux-persist
ClaudeCode 连接失败CLI/SDK 不可用或配置错误检查模型、API Key、workDir 配置

📝 Quiz — 测测你理解了多少

Q1:新增 Agent 必须完成的 3 个步骤中,最容易忘记的是哪个?
✅ 正确答案:B
在 scanner.js 中注册是最容易忘记的步骤。由于 Next.js 的动态导入限制,Agent 必须手动在 AGENT_MODULES 数组中注册,否则不会出现在 Agent 列表中。
Q2:新增 API Route 时,为什么要在 rewrites 数组前面添加排除规则?
✅ 正确答案:B
Next.js 的 rewrites 按顺序匹配。如果排除规则放在通用规则 /api/:path* 后面,新 Route 会被通用规则代理到后端,导致本地 API Route 不生效。必须放在前面。
Q3:以下哪个不是 defineAgent 的有效配置项?
✅ 正确答案:C
requiresRedux 不是 defineAgent 的有效配置项。有效的配置包括 requiresDrawio(DrawIO 分屏)、requiresXmind(XMind 分屏)、allowAddKnowledge(知识库导入)等。Redux 是全局状态管理,与 Agent 定义无关。