
mcp-agent Intent Classifier 工作流实战指南基于嵌入与 LLM 双路意图识别【免费下载链接】mcp-agentBuild effective agents using Model Context Protocol and simple workflow patterns项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-agent意图分类Intent Classification是智能 Agent 理解用户请求、决定后续动作的关键前置环节。本文以 mcp-agent 仓库中的examples/workflows/workflow_intent_classifier示例为核心完整讲解 Intent Classifier 工作流从环境搭建、双路分类器OpenAI 嵌入向量分类器与 OpenAI LLM 分类器的代码级原理、配置追踪到云端部署的全过程。读完本文你将能够基于 mcp-agent 在自己的应用中定义意图、运行分类、接入 LLM 路由并借助源码理解底层相似度计算与结构化输出机制。一、Intent Classifier 工作流概述Intent Classifier 是 mcp-agent 提供的一种工作流模式用于对自然语言请求进行意图识别与分类。它与 Router 工作流 是近亲Router 侧重于将请求路由到不同的处理分支而 Intent Classifier 更强调对请求意图本身进行语义理解和置信度打分。两者可以配合使用——先用 Intent Classifier 判定意图再按意图路由到对应处理链。从仓库结构看mcp-agent 将 Intent Classifier 实现集中在src/mcp_agent/workflows/intent_classifier/目录下按实现方式分为两大技术路线嵌入向量Embedding路线intent_classifier_embedding.py定义通用的EmbeddingIntentClassifier通过语义相似度打分完成分类intent_classifier_embedding_openai.py提供基于 OpenAI 嵌入模型的具体实现。大模型LLM路线intent_classifier_llm.py定义通用的LLMIntentClassifier借助 LLM 做推理式分类与实体抽取intent_classifier_llm_openai.py、intent_classifier_llm_anthropic.py分别对接 OpenAI 与 Anthropic 模型。本示例workflow_intent_classifier 示例同时演示了这两条路线的用法并在同一个greeting/farewell意图集上对比输出结果。二、环境搭建与项目准备1. 克隆仓库并进入示例目录git clone https://github.com/lastmile-ai/mcp-agent.git cd mcp-agent/examples/workflows/workflow_intent_classifier2. 安装 uv 并同步依赖本示例使用uv作为包管理器。若尚未安装pip install uv先同步 mcp-agent 项目根依赖uv sync再安装本示例特有依赖uv pip install -r requirements.txtrequirements.txt的内容如下查看原文# Core framework dependency mcp-agent file://../../../ # Link to the local mcp-agent project root # Additional dependencies specific to this example anthropic openai可见示例以本地文件引用方式file://链接到仓库根目录的 mcp-agent 项目同时显式安装了anthropic与openai两个模型提供方 SDK。这意味着你需要在本仓库根目录先完成 mcp-agent 的源码安装再安装示例依赖。3. 配置环境变量与密钥复制密钥模板并填入 OpenAI API Keycp mcp_agent.secrets.yaml.example mcp_agent.secrets.yaml然后打开mcp_agent.secrets.yaml查看模板$schema: ../../../schema/mcp-agent.config.schema.json openai: api_key: openai_api_key将openai_api_key替换为你的真实 Key。出于安全考虑mcp_agent.secrets.yaml应当加入.gitignore避免密钥被提交。三、配置文件逐项解析mcp_agent.config.yaml查看完整配置是本次示例的核心配置文件$schema: ../../../schema/mcp-agent.config.schema.json execution_engine: asyncio logger: type: console level: debug path: router.jsonl mcp: servers: fetch: command: uvx args: [mcp-server-fetch] filesystem: command: npx args: [-y, modelcontextprotocol/server-filesystem] openai: # Secrets (API keys, etc.) are stored in an mcp_agent.secrets.yaml file which can be gitignored default_model: gpt-4o-mini otel: enabled: false exporters: - console # To export to a collector, also include: # - otlp: # endpoint: http://localhost:4318/v1/traces service_name: WorkflowIntentClassifierExample关键字段说明配置项值作用execution_engineasyncio指定异步执行引擎mcp-agent 的默认执行方式logger.typeconsole日志输出到控制台logger.leveldebug调试级别日志便于观察分类过程logger.pathrouter.jsonl结构化日志落盘路径JSON Lines 格式mcp.serversfetch、filesystem预注册两个 MCP 服务器uvx mcp-server-fetch与npx modelcontextprotocol/server-filesystem供 Agent 工具调用openai.default_modelgpt-4o-miniLLM 分类器与嵌入分类器的默认 OpenAI 模型otel.enabledfalse是否开启 OpenTelemetry 追踪otel.exportersconsole追踪导出方式可追加otlp导出到 Collectorotel.service_nameWorkflowIntentClassifierExample追踪数据中的服务标识名注意配置中path: router.jsonl沿用了 Router 示例的命名本示例会以 JSON Lines 形式输出调试日志格式遵循logger.path设置。四、运行示例一切就绪后直接运行主程序uv run main.pymain.py查看源码的执行流程如下创建MCPApp(nameintent_classifier)应用实例通过app.tool装饰器注册一个名为example_usage的示例工具函数在async with app.run() as intent_app:中取出logger与context依次构造OpenAIEmbeddingIntentClassifier与OpenAILLMIntentClassifier各自传入相同的两个Intentgreeting与farewell对请求Hello, how are you?调用classify(request..., top_k1)并打印两类结果最后统计总运行时长。运行后在控制台会看到两行核心输出Embedding-based Intent classification results: greeting与LLM-based Intent classification results: greeting并附Total run time: x.xxs。五、两种分类器代码级原理剖析1. 意图的数据模型在 intent_classifier_base.py 中意图由 Pydantic 模型Intent描述包含四个字段字段类型说明namestr意图名称必填descriptionstr \| None意图语义描述examplesList[str]匹配该意图的示例短语metadataDict[str, str]附加元数据可辅助分类分类结果由IntentClassificationResult表示intent意图名、p_score可选置信度0~1、extracted_entities从请求中抽取的实体列表。基类IntentClassifier是抽象类继承自ContextDependent构造时必须至少提供一个Intent否则抛出ValueError子类实现抽象的classify(request, top_k1)方法并按置信度降序返回最多top_k个结果。2. 嵌入向量分类器EmbeddingIntentClassifierOpenAIEmbeddingIntentClassifier继承自EmbeddingIntentClassifierintent_classifier_embedding.py核心流程如下初始化initialize对每个意图将其name、description与所有examples合并为文本列表调用嵌入模型一次性生成向量再用mean pooling均值池化将多个向量合并成一个意图表征向量EmbeddingIntent。分类classify先对请求文本生成单个嵌入向量随后调用 embedding_base.py 中的compute_similarity_scores计算请求向量与每个意图向量的相似度当前实现使用 sklearn 的余弦相似度cosine_similarity同时预留了欧氏距离、点积等扩展位再由compute_confidence将余弦相似度直接作为置信度p_score最后按p_score降序排序并截取top_k条返回。由于示例未显式传入嵌入模型OpenAIEmbeddingIntentClassifier默认构造一个OpenAIEmbeddingModel()实例OpenAI 默认文本嵌入模型。这条路线成本低、速度快、无需额外推理适合意图集固定、请求量大的场景。3. LLM 分类器LLMIntentClassifierOpenAILLMIntentClassifier继承自LLMIntentClassifierintent_classifier_llm.py核心差异在于分类决策由大模型完成系统指令默认使用CLASSIFIER_SYSTEM_INSTRUCTION要求模型扮演精确的意图分类器可以返回一个或多个意图也可以一个都不选。提示词构造_generate_context()将全部意图编号、描述、示例、元数据格式化为提示文本随后用DEFAULT_INTENT_CLASSIFICATION_INSTRUCTION模板intent_classifier_llm.py填充context、request、top_k生成完整 prompt要求模型输出 JSON。结构化输出通过self.llm.generate_structured(messageprompt, response_modelStructuredIntentResponse, request_paramsRequestParams(strictTrue))强制模型输出符合StructuredIntentResponse的结构化结果减少类型漂移。结果校验返回的每条分类包含intent、confidencelow/medium/high三级、p_score、extracted_entities与reasoning。若模型返回的意图名不在预定义集合中会被跳过并记录异常span.record_exception最终同样截取top_k条。置信度归一LLMIntentClassificationResult._coerce_confidence校验器intent_classifier_llm.py兼容数字型置信度按[0.8, 1.0] - high、[0.5, 0.8) - medium、[0, 0.5) - low映射并将字符串统一为小写。这条路线语义理解更灵活、能抽取实体、给出推理理由但每次分类都要调用 LLM延迟与成本更高。4. 两条路线的选型建议维度嵌入分类器LLM 分类器分类原理向量余弦相似度大模型推理速度与成本快、低慢、高实体抽取不支持支持推理说明无有reasoning字段适用场景意图集固定、高并发意图复杂、需解释与抽取六、可选开启 OpenTelemetry 追踪在mcp_agent.config.yaml中把otel.enabled设为true即可为整个工作流开启 OpenTelemetry 追踪otel: enabled: true exporters: - console # - otlp: # endpoint: http://localhost:4318/v1/traces service_name: WorkflowIntentClassifierExampleexporters: [console]会在终端直接打印追踪数据适合快速调试追加otlp导出器可将 trace 发送到本地 Collector默认端点http://localhost:4318/v1/traces再配合 Jaeger 等后端在 UI 中可视化查看。结合源码看追踪埋点贯穿两条分类路线EmbeddingIntentClassifier.classify与LLMIntentClassifier.classify都会以类名开启一个 span记录请求文本、意图清单、各意图的相似度指标、top_k以及最终结果intent_classifier_embedding.py、intent_classifier_llm.py方便你定位分类不准的根因。七、Beta部署到 MCP Agent Clouda. 登录云端uv run mcp-agent loginb. 一键部署uv run mcp-agent deploy workflow-intent-classifier部署过程中系统会询问你希望如何管理密钥secrets可按需选择。c. 通过任意 MCP 客户端连接已部署的 Agent 服务部署完成后会得到一个形如https://[your-agent-server-id].deployments.mcp-agent.com/sse的 SSE 端点配合 Bearer Token 使用。Claude Desktop 集成编辑~/.claude-desktop/config.json将 Agent 服务注册为 MCP 服务器my-agent-server: { command: /path/to/npx, args: [ mcp-remote, https://[your-agent-server-id].deployments.mcp-agent.com/sse, --header, Authorization: Bearer ${BEARER_TOKEN} ], env: { BEARER_TOKEN: your-mcp-agent-cloud-api-token } }其中BEARER_TOKEN通过env注入避免 Token 明文写在命令行参数中。MCP Inspector 调试启动 MCP Inspectornpx modelcontextprotocol/inspector并按以下参数配置连接设置项值Transport TypeSSESSEhttps://[your-agent-server-id].deployments.mcp-agent.com/sseHeader NameAuthorizationBearer Tokenyour-mcp-agent-cloud-api-token[!TIP] 在 Inspector 的 Configuration 中把请求超时调长。因为 Agent 内部要进行 LLM 调用耗时必然超过普通 API 请求默认超时容易中断调用。八、接入自有应用最小可运行骨架将示例代码稍作裁剪即可在任何 mcp-agent 应用中复用import asyncio from mcp_agent.app import MCPApp from mcp_agent.workflows.intent_classifier.intent_classifier_base import Intent from mcp_agent.workflows.intent_classifier.intent_classifier_embedding_openai import ( OpenAIEmbeddingIntentClassifier, ) from mcp_agent.workflows.intent_classifier.intent_classifier_llm_openai import ( OpenAILLMIntentClassifier, ) app MCPApp(nameintent_classifier) async def main(): async with app.run() as intent_app: context intent_app.context intents [ Intent( namegreeting, descriptionA friendly greeting, examples[Hello, Hi there, Good morning], ), Intent( namefarewell, descriptionA friendly farewell, examples[Goodbye, See you later, Take care], ), ] embed_clf OpenAIEmbeddingIntentClassifier(intentsintents, contextcontext) embed_out await embed_clf.classify(requestHello, how are you?, top_k1) print(Embedding:, [(r.intent, r.p_score) for r in embed_out]) llm_clf OpenAILLMIntentClassifier(intentsintents, contextcontext) llm_out await llm_clf.classify(requestHello, how are you?, top_k1) print(LLM:, [(r.intent, r.confidence, r.p_score) for r in llm_out]) if __name__ __main__: asyncio.run(main())扩展要点自定义意图扩充examples能显著提升嵌入分类器的准确率metadata可携带标签、部门等辅助信息供 LLM 参考多结果返回把top_k调大如top_k3可同时拿到多个候选意图及其置信度用于兜底或人工确认与 Router 组合先用分类器确定意图再根据意图把请求转发给对应子 Agent形成意图分类 → 路由分发的完整链路模型切换仓库还提供intent_classifier_embedding_cohere.pyCohere 嵌入模型与intent_classifier_llm_anthropic.pyAnthropic LLM可按需替换实现。九、总结Intent Classifier 工作流是 mcp-agent 提供的高质量意图识别方案一条路线基于嵌入向量的余弦相似度实现轻量快速分类另一条路线基于 LLM 结构化输出实现灵活推理与实体抽取。通过本文你可以搭建并运行 workflow_intent_classifier 示例、读懂两种分类器的底层实现intent_classifier_embedding.py、intent_classifier_llm.py、配置 OpenTelemetry 追踪并将已部署的 Agent 以 SSE 方式接入 Claude Desktop 或 MCP Inspector。参考官方文档 Intent Classifier 与 工作流总览 可获得更多模式化设计思路。【免费下载链接】mcp-agentBuild effective agents using Model Context Protocol and simple workflow patterns项目地址: https://gitcode.com/GitHub_Trending/mc/mcp-agent创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考