LLM、AI工作流、Agent 区别与联系,以及 Skill、MCP、Rule、Hook、Plugin 完全指南

WenJun.Zuo ITer

LLM、AI工作流、Agent 完全指南

——从“对话”到“自主决策”的完整进阶路线

前言:从“聊天”到“干活”,AI 正在经历什么?

你有没有遇到过这样的情况?

你用 ChatGPT 写了一段代码,觉得挺智能。但当你让它“帮我监控服务器日志,发现异常自动发邮件通知”时,它只能给你一段代码,你自己去部署、去运行。

你问它“今天深圳天气怎么样”,它能回答。但当你让它“每天早上 8 点查天气,如果下雨就提醒我带伞”,它就无能为力了。

这不是 AI 变笨了,而是使用 AI 的方式需要升级了——从“聊天”升级到“干活”。

本文将从最基础的概念讲起,一步步带你理解:LLM、AI工作流、Agent 有什么区别和联系?Skill、MCP、Rule、Hook、Plugin 又是什么?它们怎么组合起来,让 AI 真正成为能干活的下属?

第一章:基础概念——LLM、AI工作流、Agent

1.1 LLM(大语言模型):AI 的“大脑”

生活类比:LLM 就像一个刚毕业的博士——知识渊博,什么都知道一点,但不会主动做事。你问它问题,它回答;你不问,它就等着。

技术定义:大语言模型(Large Language Model)是通过海量文本数据训练出来的深度学习模型,具备理解、生成和推理自然语言的能力。它的核心能力是文字生成、模式预测、问答

特点

  • 知识来自训练数据,无法实时更新
  • 每次回答都是独立的,不记得之前聊过什么(除非你把历史记录一起发给它)
  • 不会主动做事,只会“回答问题”

Python 示例(最原始的 LLM 调用):

1
2
3
4
5
6
7
8
9
import openai

response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "user", "content": "深圳今天天气怎么样?"}
]
)
print(response.choices[0].message.content)

Java 示例(使用 Spring AI 调用):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LLMService {

@Autowired
private ChatClient chatClient;

public String askQuestion(String question) {
ChatResponse response = chatClient.call(
new UserMessage(question)
);
return response.getResult().getOutput().getContent();
}
}

局限:LLM 本身无法获取实时信息、无法调用外部工具、无法执行多步骤任务。它只是一个“知道很多但不会做事”的大脑。

1.2 AI 工作流(Workflow):预定义好的“流水线”

生活类比:工作流就像工厂里的装配流水线——第一步拧螺丝、第二步装电池、第三步贴标签,每一步都是预先设计好的,工人(AI)只需要在指定位置做指定的事。

技术定义:AI 工作流将多个 AI 调用或传统服务编排为预定义流程,通过状态机管理任务依赖关系。开发者在设计阶段就把任务的执行路径写清楚,LLM 在这个流程里只是一个处理节点。

核心特征

  • 流程由代码预先定义,LLM 只负责生成内容,不做流程决策
  • 主控制权在预先写好的逻辑里
  • 可预测、可调试、成本低

Python 示例(一个简单的天气提醒工作流):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def weather_reminder_workflow():
# 步骤1:调用天气 API(固定)
weather = call_weather_api("深圳")

# 步骤2:判断是否下雨(固定逻辑)
if "rain" in weather.lower():
send_notification("今天深圳下雨,记得带伞!")
else:
send_notification("今天深圳天气不错!")

# 步骤3:记录日志(固定)
log_entry(weather)

# 每次运行都一样,不会变化
weather_reminder_workflow()

Java 示例(使用 Spring 状态机或顺序编排):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.springframework.stereotype.Component;

@Component
public class WeatherWorkflow {

public void execute() {
// 步骤1:获取天气
String weather = callWeatherApi("深圳");

// 步骤2:决策
if (weather.contains("rain")) {
sendNotification("今天深圳下雨,记得带伞!");
} else {
sendNotification("今天深圳天气不错!");
}

// 步骤3:记录日志
logEntry(weather);
}

private String callWeatherApi(String city) {
// 实际调用外部 API
return "rainy";
}

private void sendNotification(String msg) {
System.out.println("通知: " + msg);
}

private void logEntry(String data) {
System.out.println("日志: " + data);
}
}

适用场景:流程明确、追求可靠性的任务,如订单处理、内容审核、自动化报告生成。

1.3 AI Agent(智能体):会思考的“数字员工”

生活类比:Agent 就像一个有经验的员工——你给他一个目标“帮我安排一次深圳出差”,他自己会查机票、订酒店、规划行程、处理突发情况(比如航班取消时自动改签)。

技术定义:AI Agent 是由 LLM 驱动的系统,具备感知环境、制定计划并执行动作的能力,可以处理多轮依赖、动态变化的复杂任务。LLM 动态决定自己的处理过程和工具使用。

核心特征

  • 自主决策:Agent 自己决定“下一步做什么”
  • 动态推理:接收任务后,根据情况灵活调整
  • 工具调用:能连接外部工具与系统,获取实时信息并执行行动
  • 拥抱不确定性:Agent 的价值在于解决未知错误和应对即时变化

Python 示例(一个简易 Agent 循环):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class SimpleAgent:
def __init__(self, llm):
self.llm = llm
self.tools = [weather_api, send_email, search_web]
self.max_steps = 10

def run(self, goal):
state = {"goal": goal, "done": False}
steps = 0
while not state["done"] and steps < self.max_steps:
steps += 1
# 1. 思考:当前状态,下一步计划
thought = self.llm.think(state)
# 2. 决策:选择工具
tool_name = self.llm.decide_tool(thought, self.tools)
# 3. 执行
result = self.execute_tool(tool_name, thought)
# 4. 观察
state = self.observe(result, state)
return state

def execute_tool(self, name, params):
# 实际执行工具
pass

def observe(self, result, state):
# 更新状态
return state

Java 示例(使用 LangChain4j 或自定义 Agent 框架):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.List;
import java.util.function.Function;

public class SimpleAgent {
private LLM llm;
private List<Tool> tools;
private int maxSteps = 10;

public SimpleAgent(LLM llm, List<Tool> tools) {
this.llm = llm;
this.tools = tools;
}

public AgentResult run(String goal) {
State state = new State(goal);
int step = 0;
while (!state.isDone() && step < maxSteps) {
step++;
// 思考
Thought thought = llm.think(state);
// 决策
String toolName = llm.decideTool(thought, tools);
// 执行
ToolResult result = executeTool(toolName, thought.getParams());
// 观察更新状态
state = observe(result, state);
}
return state.toResult();
}

private ToolResult executeTool(String name, Object params) {
// 实际执行
return new ToolResult("success");
}

private State observe(ToolResult result, State state) {
state.update(result);
return state;
}
}

1.4 三者的关系:从“工具”到“流水线”到“员工”

维度 LLM(大模型) Workflow(工作流) Agent(智能体)
生活类比 刚毕业的博士 工厂流水线 有经验的员工
谁做决策 只回答问题 代码预先定义 模型自己决定
流程 单轮对话 固定步骤 动态调整
工具调用 不能 代码写死 自主选择
适用场景 问答、生成 确定性流程 复杂开放问题
成本
可预测性

演进路径

1
2
3
LLM(只会说) → Workflow(按流程做) → Agent(自己想着做)
↓ ↓ ↓
单次问答 固定流水线 自主决策执行

关键理解:这三者不是替代关系,而是不同复杂度场景的不同选择。简单任务用 LLM 调用就够了,中等复杂度的用 Workflow,真正需要自主决策的才上 Agent。

第二章:进阶组件——Skill、MCP、Rule

理解了“大脑”(LLM)、“流水线”(Workflow)、“员工”(Agent)之后,我们来看看让它们真正能干活的三个关键组件。

2.1 Skill(技能):AI 的“专业能力包”

生活类比:Skill 就像手机里的 App——你装了一个“地图 App”,手机就有了导航能力;你装了一个“计算器 App”,手机就有了计算能力。Skill 就是给 AI 安装的“能力模块”。

技术定义:Skill(技能包)是一种 AI 增强技术,它将复杂的提示工程、工具调用、工作流、模板和校验规则等元素,封装成一个可复用、可共享的“模块化包”

Skill 的标准结构(遵循 Agent Skills Specification):

1
2
3
4
5
6
my-skill/
├── SKILL.md # 核心文件(必需)
├── references/ # 参考文档(可选)
│ └── api_docs.md
└── scripts/ # 辅助脚本(可选)
└── helper.py

SKILL.md 示例(天气提醒技能):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
---
name: weather-reminder
description: 每天定时查询天气并发送提醒
license: MIT
allowed-tools: weather_api, email_sender
---

# 天气提醒技能

## 触发条件
当用户提到“天气提醒”或“天气预报”时启用。

## 执行步骤
1. 调用天气 API 获取目标城市天气
2. 判断是否包含“雨”关键词
3. 如包含,生成带“记得带伞”的提醒文案
4. 通过邮件或通知渠道发送

## 输出格式
提醒文案必须包含:🌤️ 🌧️ 图标 + 城市名 + 天气状况 + 建议

Python 中加载 Skill 的示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 从结构化目录加载 Skill
import yaml
from pathlib import Path

class SkillLoader:
def load_skill(self, skill_path):
skill_file = Path(skill_path) / "SKILL.md"
content = skill_file.read_text()
# 解析 frontmatter
parts = content.split('---')
if len(parts) >= 3:
frontmatter = yaml.safe_load(parts[1])
body = parts[2].strip()
return {
"name": frontmatter.get("name"),
"description": frontmatter.get("description"),
"instructions": body
}
return None

Java 示例(解析 Skill):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.yaml.snakeyaml.Yaml;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

public class SkillLoader {
public Skill loadSkill(Path skillPath) throws Exception {
Path mdFile = skillPath.resolve("SKILL.md");
String content = Files.readString(mdFile);
// 分割 frontmatter
String[] parts = content.split("---", 3);
if (parts.length >= 3) {
Yaml yaml = new Yaml();
Map<String, Object> frontmatter = yaml.load(parts[1]);
String body = parts[2].trim();
return new Skill(
(String) frontmatter.get("name"),
(String) frontmatter.get("description"),
body
);
}
throw new IllegalArgumentException("Invalid skill format");
}
}

2.2 MCP(模型上下文协议):AI 的“万能插头”

生活类比:MCP 就像 USB-C 接口——以前每个设备都有自己的充电口(每个工具都要单独适配),现在有了统一的接口,一个充电器能充所有设备。MCP 就是 AI 连接外部工具的“万能插头”。

技术定义:MCP(Model Context Protocol,模型上下文协议)是由 Anthropic 发起的开放标准,用于将 AI 应用连接到外部工具、数据源和资源。它通过统一的 JSON-RPC 接口,将“工具”抽象为即插即用的资源。

核心架构

1
2
3
4
5
6
7
8
9
10
┌─────────────┐     MCP协议      ┌─────────────┐
│ AI Agent │ ◄──────────────► │ MCP Server │
│ (MCP Client)│ JSON-RPC │ (工具提供方)│
└─────────────┘ └─────────────┘


┌─────────────┐
│ 外部工具 │
│ 数据库/API │
└─────────────┘

Python MCP Server 示例(使用 FastMCP):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("weather-server", json_response=True)

@mcp.tool()
def get_weather(city: str) -> str:
"""查询指定城市的天气"""
weather_data = {"深圳": "🌧️ 25°C,有雨", "北京": "☀️ 30°C,晴"}
return weather_data.get(city, "未知城市")

@mcp.resource("cities://list")
def get_cities() -> str:
return "深圳, 北京, 上海, 广州"

if __name__ == "__main__":
mcp.run()

Java MCP Server 示例(使用 Spring MCP 实现):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.springframework.mcp.server.McpServer;
import org.springframework.mcp.server.annotation.McpTool;
import org.springframework.mcp.server.annotation.McpResource;
import org.springframework.stereotype.Component;

@Component
public class WeatherMcpServer {

@McpTool(name = "get_weather", description = "查询指定城市的天气")
public String getWeather(String city) {
return switch (city) {
case "深圳" -> "🌧️ 25°C,有雨";
case "北京" -> "☀️ 30°C,晴";
default -> "未知城市";
};
}

@McpResource(uri = "cities://list")
public String getCities() {
return "深圳, 北京, 上海, 广州";
}
}

在 Agent 中连接 MCP(Python):

1
2
3
4
5
6
from mcp import MCPClient

client = MCPClient()
client.connect("weather-server")
result = client.call_tool("get_weather", {"city": "深圳"})
print(result) # 🌧️ 25°C,有雨

Java 中连接 MCP

1
2
3
4
5
6
import org.springframework.mcp.client.McpClient;

McpClient client = new McpClient();
client.connect("weather-server");
String result = client.callTool("get_weather", Map.of("city", "深圳"));
System.out.println(result);

2.3 Rule(规则):AI 的“行为准则”

生活类比:Rule 就像公司的员工手册——规定“上班不能穿拖鞋”、“邮件必须用公司签名”、“代码必须写注释”。员工不需要每次被提醒,这些规则会自动生效。

技术定义:Rule(规则)是对 AI 行为施加的硬性或软性约束,用于确保输出符合安全、合规、风格等要求。它本质上是全局或局部的 prompt 约束,每次调用都自动塞进上下文。

Rule 格式示例(常用于 .cursor/rules/):

1
2
3
4
5
6
7
8
9
10
11
12
# .cursor/rules/coding-style.mdc
---
description: Java 代码规范
globs: ["**/*.java"]
alwaysApply: true
---

## 代码规范
1. 所有公共方法必须写 JavaDoc
2. 类名使用大驼峰命名(PascalCase)
3. 方法名使用小驼峰命名(camelCase)
4. 禁止使用 System.out.println(),必须用 Logger

Python 中使用 Rule(模拟)

1
2
3
4
5
6
7
8
9
10
11
12
class RuleEngine:
def __init__(self):
self.rules = []

def add_rule(self, rule):
self.rules.append(rule)

def apply(self, context, message):
for rule in self.rules:
if rule.matches(context):
message = rule.enforce(message)
return message

Java 中使用 Rule(基于 MVEL 或自定义)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.function.BiFunction;

public class Rule {
private String description;
private BiFunction<Context, String, String> enforce;

public Rule(String desc, BiFunction<Context, String, String> enforce) {
this.description = desc;
this.enforce = enforce;
}

public String apply(Context ctx, String input) {
return enforce.apply(ctx, input);
}
}

2.4 三者的关系:一张表看懂

维度 Skill(技能) MCP(协议) Rule(规则)
生活类比 手机 App USB-C 接口 员工手册
本质 能力封装 连接标准 行为约束
作用 教 AI “怎么做” 让 AI “能碰到什么” 管 AI “应该怎样”
触发方式 按需加载 调用时连接 始终生效
可复用 ✅ 跨任务复用 ✅ 跨工具复用 ✅ 跨任务复用

第三章:扩展能力——Hook 与 Plugin

3.1 Hook(钩子):AI 的“自动触发器”

生活类比:Hook 就像智能家居的自动化规则——“开门时自动开灯”、“有人经过时自动录像”。你不需要每次手动操作,系统会在特定事件发生时自动执行预设动作。

技术定义:Hook(钩子)是一种事件驱动的自动化机制,在 Agent 或系统的特定生命周期节点(如工具调用前、文件写入后、会话结束时)自动执行预定义的脚本或逻辑。

Hook 的核心特征

  • 确定性触发:只要事件发生,Hook 一定执行,不依赖模型决策
  • 零上下文占用:Hook 作为外部脚本运行,默认不占用 LLM 的上下文窗口
  • 硬约束:Hook 可以强制执行规则,不像 Skill 那样“建议”AI 怎么做

典型 Hook 事件

Hook 事件 触发时机 典型用途
PreToolUse 工具调用前 权限校验、参数验证、操作审批
PostToolUse 工具调用后 日志记录、结果审计、自动格式化
PreFileWrite 文件写入前 代码规范检查、路径校验
PostFileWrite 文件写入后 自动格式化、Lint 检查
Stop 会话结束时 自动保存对话、生成摘要

Python Hook 示例(Claude Code 风格的 PreToolUse):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python3
# .claude/hooks/check-permission.py
import json
import sys

def is_dangerous(command):
dangerous = ['rm -rf', 'sudo', 'chmod 777']
return any(p in command for p in dangerous)

if __name__ == "__main__":
input_data = json.load(sys.stdin)
tool_name = input_data.get('tool_name', '')
tool_input = input_data.get('tool_input', {})

if tool_name == 'Bash':
command = tool_input.get('command', '')
if is_dangerous(command):
response = {"decision": "block", "reason": f"危险命令被拦截: {command}"}
print(json.dumps(response))
sys.exit(0)

print(json.dumps({"decision": "allow"}))

Java Hook 示例(使用 AgentScope 或自建拦截器):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import io.agentscope.core.middleware.MiddlewareBase;
import io.agentscope.core.middleware.MiddlewareContext;
import reactor.core.publisher.Mono;

public class PermissionCheckHook extends MiddlewareBase {

@Override
public Mono<HookEvent> onActing(MiddlewareContext ctx, HookEvent event) {
for (var toolCall : event.getToolCalls()) {
if (toolCall.getName().equals("Bash")) {
String command = toolCall.getArguments().get("command");
if (isDangerous(command)) {
return Mono.error(new SecurityException(
"危险命令被拦截: " + command
));
}
}
}
return Mono.just(event);
}

private boolean isDangerous(String cmd) {
String[] patterns = {"rm -rf", "sudo", "chmod 777"};
for (String p : patterns) {
if (cmd.contains(p)) return true;
}
return false;
}
}

Hook 配置示例(JSON):

1
2
3
4
5
6
7
8
9
10
{
"hooks": {
"PreToolUse": [
{ "matcher": "Bash", "command": ".claude/hooks/check-permission.py" }
],
"PostToolUse": [
{ "matcher": "Write", "command": ".claude/hooks/auto-format.py" }
]
}
}

3.2 Plugin(插件):AI 的“能力分发工具箱”

生活类比:Plugin 就像手机应用商店里的 App 安装包——一个安装包可以把“地图导航 + 语音助手 + 离线地图”一起打包,用户一键安装,所有功能同时生效。

技术定义:Plugin(插件)是一个打包和分发单元,将 Skills、Agents、Hooks、MCP Servers、Commands 等多种扩展能力捆绑到一个可安装的包中。

Plugin 的核心特征

  • 打包层:Plugin 本身不创造新能力,而是把已有的能力“装进箱子”
  • 命名空间隔离:Plugin 中的 Skill 会以插件名为前缀(如 my-plugin:greet
  • 可分发:通过 Plugin Marketplace 或 --plugin-dir 分享给团队或社区

Plugin 目录结构

1
2
3
4
5
6
7
8
9
10
team-code-review/                          # 插件根目录
├── .claude-plugin/
│ └── plugin.json # 插件清单
├── skills/
│ └── code-review/
│ └── SKILL.md # 代码审查技能
├── hooks/
│ └── hooks.json # 自动化钩子
└── mcp/
└── mcp.json # MCP 服务配置

plugin.json 示例

1
2
3
4
5
6
7
8
9
10
11
{
"id": "team-code-review",
"name": "团队代码审查插件",
"version": "1.0.0",
"description": "包含代码审查 Skill、自动格式化 Hook 和静态分析 MCP",
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {}
}
}

Python 加载 Plugin

1
2
3
4
5
6
7
8
9
10
11
# 加载本地插件
from claude_agent_sdk import query

async def main():
async for message in query(
prompt="帮我审查代码",
options={
"plugins": [{"type": "local", "path": "./team-code-review"}]
}
):
print(message)

Java 加载 Plugin(Spring AI 风格):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import org.springframework.ai.plugin.Plugin;
import org.springframework.ai.plugin.PluginRegistry;

@Component
public class CodeReviewPlugin implements Plugin {
@Override
public String getId() { return "team-code-review"; }
@Override
public String getName() { return "团队代码审查插件"; }

public List<Skill> getSkills() {
return List.of(new CodeReviewSkill());
}
public List<Hook> getHooks() {
return List.of(new AutoFormatHook());
}
}

// 注册
@Autowired
private PluginRegistry registry;
registry.register(new CodeReviewPlugin());

3.3 Hook vs Plugin 对比

维度 Hook(钩子) Plugin(插件)
生活类比 智能家居自动化规则 手机 App 安装包
本质 事件驱动的自动化脚本 能力的打包分发单元
核心作用 “在特定时刻自动做某事” “把一堆能力打包发给别人”
触发方式 事件自动触发(确定性) 安装后按需使用
占用上下文 不占用(外部脚本运行) 取决于内容
是否创造新能力 ❌ 不创造,只拦截/增强 ❌ 不创造,只打包

第四章:完整实战——从零搭建一个智能运维助手

场景设定

我们要搭建一个智能运维助手,它能:

  1. 每天自动检查服务器状态(Rule 约束行为)
  2. 发现异常时分析日志(Skill 封装分析流程)
  3. 通过 MCP 连接监控系统和通知服务
  4. Agent 自主决策如何处理异常
  5. 使用 Hook 进行安全拦截和审计
  6. 最终打包成 Plugin 供团队使用

4.1 定义 Rule(Python + Java)

Python Rule 配置(.cursor/rules/ops.mdc):

1
2
3
4
5
6
7
8
9
---
description: 运维助手行为规范
alwaysApply: true
---

1. 所有操作必须记录操作日志
2. 涉及生产环境的操作必须二次确认
3. 禁止直接修改数据库,必须通过 API
4. 发现异常时,优先尝试自动恢复,失败后再告警

Java Rule 实现

1
2
3
4
5
6
7
8
9
10
import java.util.function.BiFunction;

public class OpsRule {
public static Rule requireLogging() {
return new Rule("记录日志", (ctx, msg) -> {
System.out.println("[AUDIT] " + ctx.getSessionId() + " -> " + msg);
return msg;
});
}
}

4.2 编写 Skill(日志分析)

Python Skill 定义(skills/log-analyzer/SKILL.md):

1
2
3
4
5
6
7
8
9
10
11
12
---
name: log-analyzer
description: 分析系统日志,定位异常根因
---

# 日志分析技能

## 执行步骤
1. 通过 MCP 连接日志数据库,获取最近 30 分钟的 ERROR 日志
2. 按时间排序,识别异常模式
3. 对每条异常,匹配知识库(已知问题 → 返回解决方案)
4. 生成分析报告(摘要、详情、建议)

Java 中调用 Skill

1
2
3
4
5
6
7
8
Skill logAnalyzer = new Skill("log-analyzer", 
context -> {
// 通过 MCP 查日志
String logs = mcpClient.callTool("logdb", "query", Map.of("time", "30m"));
// 分析逻辑
return analyze(logs);
}
);

4.3 配置 MCP Server(Python + Java)

Python MCP(通知服务):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("notification-server")

@mcp.tool()
def send_alert(service: str, level: str, message: str) -> str:
print(f"[{level}] {service}: {message}")
return f"告警已发送: {service}"

@mcp.tool()
def get_service_status(service: str) -> dict:
return {"service": service, "status": "running", "uptime": "72h"}

mcp.run()

Java MCP(相同功能):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.springframework.mcp.server.annotation.McpTool;
import org.springframework.stereotype.Component;

@Component
public class NotificationMcpServer {

@McpTool(name = "send_alert")
public String sendAlert(String service, String level, String message) {
System.out.printf("[%s] %s: %s%n", level, service, message);
return "告警已发送: " + service;
}

@McpTool(name = "get_service_status")
public Map<String, Object> getStatus(String service) {
return Map.of("service", service, "status", "running", "uptime", "72h");
}
}

4.4 Hook 安全拦截(Python + Java)

Python Hook(PreToolUse 拦截):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# hooks/block-dangerous.py
import json, sys

dangerous = ['rm -rf', 'dd if=']

def main():
data = json.load(sys.stdin)
cmd = data.get('tool_input', {}).get('command', '')
if any(p in cmd for p in dangerous):
print(json.dumps({"decision": "block", "reason": "危险命令"}))
return
print(json.dumps({"decision": "allow"}))

if __name__ == "__main__":
main()

Java Hook(AgentScope 风格):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SecurityHook extends MiddlewareBase {
@Override
public Mono<HookEvent> onActing(MiddlewareContext ctx, HookEvent event) {
for (var tc : event.getToolCalls()) {
if (tc.getName().equals("Bash")) {
String cmd = tc.getArguments().get("command");
if (cmd.contains("rm -rf") || cmd.contains("dd if=")) {
return Mono.error(new SecurityException("拦截危险命令"));
}
}
}
return Mono.just(event);
}
}

4.5 打包为 Plugin

plugin.json

1
2
3
4
5
6
{
"id": "ops-assistant",
"name": "智能运维助手",
"version": "1.0.0",
"description": "包含日志分析 Skill、安全 Hook、监控 MCP"
}

目录结构

1
2
3
4
5
ops-assistant/
├── .claude-plugin/plugin.json
├── skills/log-analyzer/SKILL.md
├── hooks/hooks.json
└── mcp/mcp.json

4.6 Agent 自主运行

Python Agent 启动

1
2
3
4
5
6
7
8
9
10
11
from agent_sdk import create_agent

agent = create_agent(
model="gpt-4",
skills=[log_analyzer],
hooks=[security_hook],
mcp_servers=[notification_mcp, log_mcp],
rules=[ops_rules]
)

agent.run("监控订单服务,发现异常自动处理")

Java Agent 启动(使用 LangChain4j):

1
2
3
4
5
6
7
8
9
Agent agent = Agent.builder()
.model("gpt-4")
.skills(List.of(logAnalyzer))
.hooks(List.of(securityHook))
.mcps(List.of(notificationMcp, logMcp))
.rules(List.of(opsRule))
.build();

agent.run("监控订单服务,发现异常自动处理");

完整执行流程

  1. Agent 每 30 秒调用 MCP get_service_status
  2. 发现 CPU 异常 → 加载 Skill 分析日志
  3. Hook 拦截危险命令,确保安全
  4. Agent 自主决定:重启服务 → 发告警 → 继续监控

第五章:选型指南——什么时候用什么

5.1 场景 → 方案对照

场景 推荐方案 原因
单次问答、内容生成 LLM 调用 简单、低成本
固定流程的自动化任务 Workflow 可预测、易调试
需要灵活决策的复杂任务 Agent 自主处理变化
反复执行的标准化任务 Skill 封装 一次封装,重复使用
需要连接外部工具 MCP 统一标准,即插即用
对 AI 行为有固定要求 Rule 始终生效,无需提醒
需要在特定时刻自动执行 Hook 事件驱动,零上下文
需要分发给团队或社区 Plugin 打包安装,统一管理

5.2 选择 Workflow 还是 Agent?

Workflow 和 Agent 的根本区别,不在于是否用了 LLM,而在于“下一步做什么”这个决策由谁做出。

判断维度 选 Workflow 选 Agent
步骤是否明确 ✅ 每一步都清楚 ❌ 需要动态判断
是否需要人工干预 ✅ 可以预设分支 ❌ 需要自主处理异常
对成本敏感 ✅ 成本可控 ❌ 成本较高
对可预测性要求高 ✅ 输出可预期 ❌ 可能走不同路径

5.3 何时使用 Hook 与 Plugin?

  • Hook:需要强制执行的安全策略、审计日志、自动格式化。
  • Plugin:需要将多个能力打包分发给团队,或开源分享。

最佳实践:80% 的场景用 Skill + MCP 足够,Hook 和 Plugin 解决规模化后的治理问题。

第六章:高阶技巧与避坑指南

6.1 技巧

  1. Skill 要单一职责:一个 Skill 只做一件事。
  2. MCP 工具设计清晰:名称、描述、参数明确。
  3. Rule 简短精炼:控制在 500 行以内,用 globs 限定范围。
  4. Hook 脚本短小:只做确定性判断,复杂逻辑交给 Skill。
  5. Plugin 先试用再分发:先在单项目验证,再打包。

6.2 避坑指南

坑 1:把 Workflow 当 Agent 卖
❌ 画流程图定义每一步 → 那是 Workflow。
✅ 让模型自己决定下一步 → 才是 Agent。

坑 2:一上来就上 Agent
❌ 从最复杂的方案开始。
✅ 从最简单的方案开始,只在必要时增加复杂性。

坑 3:Skill 和 MCP 分不清
✅ Skill 教“怎么做”,MCP 告诉“能碰到什么”。

坑 4:Hook 写得太复杂
❌ 在 Hook 里做 AI 推理。
✅ Hook 只做事件触发的小型控制。

坑 5:过早引入 Plugin
❌ 项目初期就设计 Plugin 架构。
✅ Skill 起步,遇到真实瓶颈再加 Plugin。

第七章:总结与完整图谱

7.1 一句话总结每个概念

概念 一句话总结
LLM 知道很多但不会主动做事的“大脑”
Agent 会自己思考决策的“数字员工”
Workflow 预定义好每一步的“流水线”
Rule 始终生效的行为“护栏”
Skill 封装好最佳实践的“能力包”
MCP 统一连接外部工具的“万能插头”
Hook 事件驱动的“自动触发器”
Plugin 打包分发能力的“工具箱”

7.2 完整图谱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
┌─────────────────────────────────────────────────────────────────────────┐
│ AI 工程化完整概念图谱 │
├─────────────────────────────────────────────────────────────────────────┤
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ Plugin(分发层:打包+安装) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────────────────────────┼────────────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌──────────────┐ ┌───────────────────┐ ┌──────────────────┐ │
│ │ Skill │ │ Hook │ │ MCP Server │ │
│ │ (能力层) │ │ (自动化层) │ │ (集成层) │ │
│ └──────────────┘ └───────────────────┘ └──────────────────┘ │
│ │ │ │ │
│ └────────────────────────┼────────────────────────┘ │
│ ▼ │
│ ┌───────────────────┐ │
│ │ Rule(规则层) │ │
│ └───────────────────┘ │
│ ▼ │
│ ┌───────────────────┐ │
│ │ Agent(执行层) │ │
│ └───────────────────┘ │
│ ▼ │
│ ┌───────────────────┐ │
│ │ LLM(基础层) │ │
│ └───────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘

7.3 进阶学习路径

  1. 入门:理解 LLM、Workflow、Agent 区别
  2. 进阶:掌握 Skill 和 MCP 的编写
  3. 熟练:配置 Rule 和 Hook 实现治理
  4. 精通:设计 Plugin 并分发给团队

7.4 写在最后

AI 工程化的核心,不是让 AI 更智能,而是让 AI 更可控、更可靠、更可复用

  • LLM → 智能原料
  • Workflow → 确定性流程
  • Agent → 自主决策
  • Skill → 知识沉淀
  • MCP → 标准连接
  • Rule → 安全网
  • Hook → 自动化触发器
  • Plugin → 能力分发

从今天开始,试着把重复的任务封装成 Skill,用 Rule 约束行为,用 MCP 连接工具,用 Hook 实现自动化,最后打包成 Plugin 分享给团队——让 AI 从“聊天的朋友”变成“能干活的下属”。

附录:快速参考卡片

概念 关键特征 典型场景
LLM 生成、推理、问答 聊天、写作、代码生成
Workflow 固定步骤、可预测 订单处理、内容审核
Agent 动态推理、工具调用 复杂任务、异常处理
Skill 可复用、按需加载 日志分析、代码审查
MCP 统一接口、即插即用 查数据库、发通知
Rule 始终生效、自动执行 代码规范、安全红线
Hook 事件触发、零上下文 权限校验、自动格式化
Plugin 打包分发、命名隔离 团队规范、开源分享
  • 标题: LLM、AI工作流、Agent 区别与联系,以及 Skill、MCP、Rule、Hook、Plugin 完全指南
  • 作者: WenJun.Zuo
  • 创建于 : 2026-08-15 14:17:00
  • 更新于 : 2026-08-15 14:17:00
  • 链接: https://www.zuowenjun.cn//2026/03/28/ai-workflow-agent-spec/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
 评论
此页目录
LLM、AI工作流、Agent 区别与联系,以及 Skill、MCP、Rule、Hook、Plugin 完全指南