Sequential MCP 服务
Sequential 是 Claude Code 生态系统中的流程化代码分析服务,专门处理需要按顺序执行的复杂代码分析和重构任务。
服务概述
Sequential 通过 Model Context Protocol (MCP) 提供:
- 流程化代码分析
- 步骤化重构指导
- 渐进式代码改进
- 阶段性进度追踪
- 任务依赖管理
快速开始
安装配置
1. 安装服务
bash
# 全局安装
npm install -g @claude/sequential-mcp-server
# 或作为项目依赖
npm install --save-dev @claude/sequential-mcp-server2. 配置 MCP 客户端
json
// claude.config.json
{
"mcpServers": {
"sequential": {
"command": "sequential-mcp-server",
"args": ["--workspace", "./", "--config", "./sequential.config.js"],
"env": {
"SEQUENTIAL_LOG_LEVEL": "info",
"SEQUENTIAL_CACHE_DIR": "./.sequential/cache"
}
}
}
}3. 启动服务
bash
# 直接启动
sequential-mcp-server --workspace ./my-project
# 或通过 Claude CLI
claude mcp start sequential核心功能
1. 流程化代码分析
创建分析流程
javascript
// 创建新的分析流程
const workflow = await mcp.call('sequential', 'createWorkflow', {
name: '用户模块重构',
description: '对用户管理模块进行全面重构',
scope: ['src/modules/user/**'],
type: 'refactoring'
});
console.log(workflow);响应示例:
json
{
"success": true,
"data": {
"workflowId": "wf_001",
"name": "用户模块重构",
"status": "created",
"steps": [
{
"id": "step_001",
"name": "代码分析",
"type": "analysis",
"status": "pending",
"description": "分析现有代码结构和质量",
"estimatedDuration": "30min"
},
{
"id": "step_002",
"name": "问题识别",
"type": "identification",
"status": "pending",
"description": "识别代码中的问题和改进点",
"dependencies": ["step_001"],
"estimatedDuration": "20min"
},
{
"id": "step_003",
"name": "重构方案",
"type": "planning",
"status": "pending",
"description": "制定详细的重构方案",
"dependencies": ["step_002"],
"estimatedDuration": "45min"
},
{
"id": "step_004",
"name": "代码重构",
"type": "refactoring",
"status": "pending",
"description": "执行代码重构",
"dependencies": ["step_003"],
"estimatedDuration": "2h"
},
{
"id": "step_005",
"name": "测试验证",
"type": "testing",
"status": "pending",
"description": "验证重构后的代码功能",
"dependencies": ["step_004"],
"estimatedDuration": "30min"
}
],
"createdAt": "2024-01-20T10:00:00Z",
"estimatedTotal": "3h 45min"
}
}执行流程步骤
javascript
// 开始执行流程
const execution = await mcp.call('sequential', 'startWorkflow', {
workflowId: 'wf_001',
autoAdvance: true // 自动执行下一步
});
// 执行特定步骤
const stepResult = await mcp.call('sequential', 'executeStep', {
workflowId: 'wf_001',
stepId: 'step_001'
});2. 步骤化重构指导
重构流程模板
javascript
// 获取预定义的重构模板
const templates = await mcp.call('sequential', 'getTemplates', {
type: 'refactoring',
language: 'javascript'
});
// 使用模板创建流程
const workflow = await mcp.call('sequential', 'createFromTemplate', {
templateId: 'react-component-refactor',
target: 'src/components/UserProfile.jsx',
parameters: {
extractHooks: true,
addTypeScript: true,
optimizePerformance: true
}
});React 组件重构模板:
json
{
"templateId": "react-component-refactor",
"name": "React 组件重构",
"description": "系统化重构 React 组件",
"steps": [
{
"name": "组件分析",
"type": "analysis",
"actions": [
"分析组件复杂度",
"识别状态管理模式",
"检查性能问题",
"评估可测试性"
],
"outputs": ["analysis_report.md"]
},
{
"name": "代码拆分",
"type": "refactoring",
"description": "将大组件拆分为小组件",
"actions": [
"识别可提取的子组件",
"分离业务逻辑和UI逻辑",
"提取自定义Hook",
"优化状态结构"
],
"validations": [
"组件大小合理 (<200行)",
"职责单一",
"可复用性高"
]
},
{
"name": "性能优化",
"type": "optimization",
"actions": [
"添加 React.memo",
"优化重渲染",
"使用 useMemo/useCallback",
"懒加载优化"
],
"metrics": [
"渲染次数减少",
"内存使用优化",
"首屏加载时间"
]
},
{
"name": "类型安全",
"type": "enhancement",
"condition": "parameters.addTypeScript",
"actions": [
"添加 TypeScript 类型",
"定义 Props 接口",
"添加泛型支持",
"类型推导优化"
]
},
{
"name": "测试完善",
"type": "testing",
"actions": [
"编写单元测试",
"添加集成测试",
"快照测试更新",
"测试覆盖率检查"
],
"requirements": [
"测试覆盖率 >= 80%",
"所有关键路径有测试",
"Mock 外部依赖"
]
}
]
}执行重构步骤
javascript
// 执行代码拆分步骤
const refactorResult = await mcp.call('sequential', 'executeStep', {
workflowId: 'wf_react_001',
stepId: 'code_splitting'
});
console.log(refactorResult);步骤执行结果:
json
{
"success": true,
"stepId": "code_splitting",
"status": "completed",
"duration": "25min",
"results": {
"extractedComponents": [
{
"name": "UserAvatar",
"file": "src/components/UserProfile/UserAvatar.jsx",
"linesOfCode": 45,
"purpose": "显示用户头像和在线状态"
},
{
"name": "UserInfo",
"file": "src/components/UserProfile/UserInfo.jsx",
"linesOfCode": 32,
"purpose": "显示用户基本信息"
}
],
"extractedHooks": [
{
"name": "useUserData",
"file": "src/hooks/useUserData.js",
"purpose": "管理用户数据获取和缓存"
}
],
"reducedComplexity": {
"before": 15,
"after": 8,
"improvement": "47%"
},
"codeChanges": {
"filesModified": 3,
"filesCreated": 3,
"linesAdded": 125,
"linesRemoved": 89
}
},
"nextSteps": [
{
"stepId": "performance_optimization",
"readyToExecute": true,
"estimatedDuration": "20min"
}
],
"recommendations": [
"考虑将 UserAvatar 组件添加到设计系统",
"useUserData Hook 可以在其他用户相关组件中复用",
"建议为新组件添加 Storybook 文档"
]
}3. 渐进式代码改进
创建改进计划
javascript
// 创建渐进式改进计划
const improvement = await mcp.call('sequential', 'createImprovementPlan', {
scope: 'src/services/api',
goals: [
'improve_error_handling',
'add_type_safety',
'optimize_performance',
'enhance_testability'
],
timeline: '2weeks',
riskTolerance: 'low' // low, medium, high
});改进计划示例:
json
{
"planId": "imp_001",
"name": "API 服务改进计划",
"timeline": "2weeks",
"phases": [
{
"phase": 1,
"name": "基础改进",
"duration": "3days",
"risk": "low",
"steps": [
{
"name": "添加错误处理",
"description": "为所有API调用添加统一的错误处理",
"impact": "high",
"effort": "medium"
},
{
"name": "请求/响应日志",
"description": "添加详细的请求和响应日志",
"impact": "high",
"effort": "low"
}
]
},
{
"phase": 2,
"name": "类型安全",
"duration": "4days",
"risk": "low",
"dependencies": ["phase_1"],
"steps": [
{
"name": "TypeScript 迁移",
"description": "将 JavaScript 文件迁移到 TypeScript",
"impact": "high",
"effort": "high"
},
{
"name": "API 类型定义",
"description": "为所有 API 接口定义 TypeScript 类型",
"impact": "medium",
"effort": "medium"
}
]
},
{
"phase": 3,
"name": "性能优化",
"duration": "4days",
"risk": "medium",
"dependencies": ["phase_2"],
"steps": [
{
"name": "请求缓存",
"description": "实现智能的请求缓存机制",
"impact": "high",
"effort": "high"
},
{
"name": "并发控制",
"description": "添加请求并发控制和队列管理",
"impact": "medium",
"effort": "medium"
}
]
},
{
"phase": 4,
"name": "测试增强",
"duration": "3days",
"risk": "low",
"dependencies": ["phase_3"],
"steps": [
{
"name": "单元测试",
"description": "为所有 API 服务添加单元测试",
"impact": "high",
"effort": "high"
},
{
"name": "集成测试",
"description": "添加 API 集成测试",
"impact": "medium",
"effort": "medium"
}
]
}
],
"rollbackPlan": {
"strategy": "git_branch_per_phase",
"checkpoints": ["phase_1", "phase_2", "phase_3"],
"rollbackProcedure": "revert_to_checkpoint"
}
}执行改进阶段
javascript
// 执行特定阶段
const phaseResult = await mcp.call('sequential', 'executePhase', {
planId: 'imp_001',
phaseId: 'phase_1',
options: {
createBackup: true,
runTests: true,
validateChanges: true
}
});4. 阶段性进度追踪
获取流程状态
javascript
// 获取工作流状态
const status = await mcp.call('sequential', 'getWorkflowStatus', {
workflowId: 'wf_001'
});
// 获取详细进度报告
const progress = await mcp.call('sequential', 'getProgressReport', {
workflowId: 'wf_001',
includeMetrics: true
});进度报告示例:
json
{
"workflowId": "wf_001",
"name": "用户模块重构",
"status": "in_progress",
"progress": {
"completedSteps": 3,
"totalSteps": 5,
"percentage": 60
},
"timeline": {
"startedAt": "2024-01-20T10:00:00Z",
"estimatedCompletion": "2024-01-20T13:45:00Z",
"actualDuration": "2h 15min",
"remainingDuration": "1h 30min"
},
"currentStep": {
"id": "step_004",
"name": "代码重构",
"status": "in_progress",
"progress": 75,
"startedAt": "2024-01-20T12:00:00Z",
"estimatedCompletion": "2024-01-20T14:00:00Z"
},
"completedSteps": [
{
"id": "step_001",
"name": "代码分析",
"completedAt": "2024-01-20T10:30:00Z",
"duration": "30min",
"status": "completed",
"results": {
"filesAnalyzed": 15,
"issuesIdentified": 23,
"complexityScore": 8.5
}
},
{
"id": "step_002",
"name": "问题识别",
"completedAt": "2024-01-20T11:00:00Z",
"duration": "25min",
"status": "completed",
"results": {
"criticalIssues": 3,
"majorIssues": 8,
"minorIssues": 12
}
},
{
"id": "step_003",
"name": "重构方案",
"completedAt": "2024-01-20T12:00:00Z",
"duration": "40min",
"status": "completed",
"results": {
"refactoringTasks": 12,
"estimatedEffort": "3h",
"riskAssessment": "low"
}
}
],
"metrics": {
"codeQuality": {
"before": 6.2,
"current": 7.8,
"target": 8.5,
"improvement": "26%"
},
"testCoverage": {
"before": 65,
"current": 78,
"target": 85,
"improvement": "20%"
},
"performance": {
"buildTime": {
"before": "45s",
"current": "38s",
"improvement": "16%"
}
}
},
"nextSteps": [
{
"id": "step_005",
"name": "测试验证",
"scheduledStart": "2024-01-20T14:00:00Z",
"dependencies": ["step_004"],
"readyToExecute": false
}
]
}生成流程报告
javascript
// 生成完整的流程报告
const report = await mcp.call('sequential', 'generateReport', {
workflowId: 'wf_001',
format: 'html', // html, pdf, markdown
includeDetails: true,
includeMetrics: true,
includeRecommendations: true
});5. 任务依赖管理
定义依赖关系
javascript
// 创建复杂的依赖流程
const complexWorkflow = await mcp.call('sequential', 'createWorkflow', {
name: '全栈应用重构',
steps: [
{
id: 'database_migration',
name: '数据库迁移',
type: 'database',
dependencies: []
},
{
id: 'api_refactor',
name: 'API 重构',
type: 'backend',
dependencies: ['database_migration']
},
{
id: 'frontend_update',
name: '前端更新',
type: 'frontend',
dependencies: ['api_refactor']
},
{
id: 'integration_test',
name: '集成测试',
type: 'testing',
dependencies: ['api_refactor', 'frontend_update'],
executionMode: 'wait_all' // wait_all, wait_any
}
]
});依赖图可视化
javascript
// 生成依赖关系图
const dependencyGraph = await mcp.call('sequential', 'getDependencyGraph', {
workflowId: 'wf_complex_001',
format: 'mermaid'
});
console.log(dependencyGraph.mermaidCode);生成的依赖图:
高级配置
服务配置文件
javascript
// sequential.config.js
export default {
// 执行配置
execution: {
// 并发执行
concurrency: {
enabled: true,
maxParallel: 3,
timeout: '30min'
},
// 错误处理
errorHandling: {
retryAttempts: 3,
retryDelay: '5s',
stopOnError: false,
rollbackOnFailure: true
},
// 进度保存
persistence: {
enabled: true,
saveInterval: '5min',
stateFile: '.sequential/state.json'
}
},
// 模板配置
templates: {
directory: './templates/sequential',
autoReload: true,
validation: true
},
// 通知配置
notifications: {
channels: ['console', 'webhook'],
events: [
'workflow_started',
'workflow_completed',
'workflow_failed',
'step_completed',
'milestone_reached'
],
webhook: {
url: process.env.SEQUENTIAL_WEBHOOK_URL,
headers: {
'Authorization': `Bearer ${process.env.WEBHOOK_TOKEN}`
}
}
},
// 集成配置
integrations: {
// Git 集成
git: {
enabled: true,
createBranches: true,
branchPrefix: 'sequential/',
commitMessages: true,
tagMilestones: true
},
// 测试集成
testing: {
enabled: true,
runAfterStep: true,
stopOnTestFailure: true,
coverageThreshold: 80
},
// 构建集成
build: {
enabled: true,
runAfterPhase: true,
validateBuild: true
}
}
};自定义步骤类型
javascript
// steps/custom-analysis-step.js
import { BaseStep } from '@claude/sequential-mcp-server';
export default class CustomAnalysisStep extends BaseStep {
constructor(options) {
super(options);
this.type = 'custom-analysis';
}
async execute(context) {
const { files, options } = context;
// 自定义分析逻辑
const analysisResults = await this.performAnalysis(files);
// 生成报告
const report = await this.generateReport(analysisResults);
// 返回结果
return {
success: true,
results: analysisResults,
artifacts: [report],
nextStepRecommendations: this.getRecommendations(analysisResults)
};
}
async performAnalysis(files) {
// 实现具体的分析逻辑
const results = {
complexity: {},
dependencies: {},
patterns: {},
issues: []
};
for (const file of files) {
// 分析每个文件
results.complexity[file.path] = this.analyzeComplexity(file);
results.dependencies[file.path] = this.analyzeDependencies(file);
results.patterns[file.path] = this.identifyPatterns(file);
results.issues.push(...this.findIssues(file));
}
return results;
}
async generateReport(results) {
// 生成分析报告
const reportContent = `
# 自定义代码分析报告
## 复杂度分析
${this.formatComplexityResults(results.complexity)}
## 依赖分析
${this.formatDependencyResults(results.dependencies)}
## 模式识别
${this.formatPatternResults(results.patterns)}
## 问题清单
${this.formatIssueResults(results.issues)}
`;
return {
type: 'report',
format: 'markdown',
content: reportContent,
filename: 'custom-analysis-report.md'
};
}
}集成示例
CI/CD 集成
yaml
# .github/workflows/sequential.yml
name: Sequential Code Improvement
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
sequential-analysis:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run Sequential Analysis
run: |
npx sequential-mcp-server \
--workflow analysis-workflow.yaml \
--output analysis-results.json
- name: Upload Results
uses: actions/upload-artifact@v3
with:
name: sequential-results
path: analysis-results.json
- name: Comment PR
if: github.event_name == 'pull_request'
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const results = JSON.parse(fs.readFileSync('analysis-results.json'));
const comment = `## Sequential 分析报告
- 工作流状态: ${results.status}
- 完成步骤: ${results.completedSteps}/${results.totalSteps}
- 代码质量提升: ${results.qualityImprovement}%
- 发现问题: ${results.issuesFound}
详细报告请查看 Actions artifacts。`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});IDE 扩展集成
javascript
// vscode-extension/src/sequential-provider.js
import * as vscode from 'vscode';
import { MCPClient } from '@claude/mcp-client';
class SequentialProvider {
constructor() {
this.client = new MCPClient('sequential');
this.statusBar = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left
);
}
async startWorkflow(files) {
// 显示选择模板的快速选择
const templates = await this.client.call('getTemplates');
const selected = await vscode.window.showQuickPick(
templates.map(t => ({ label: t.name, description: t.description, id: t.id })),
{ placeHolder: '选择重构模板' }
);
if (!selected) return;
// 创建工作流
const workflow = await this.client.call('createFromTemplate', {
templateId: selected.id,
files: files.map(f => f.fsPath)
});
// 显示进度
this.showProgress(workflow.workflowId);
// 开始执行
await this.client.call('startWorkflow', {
workflowId: workflow.workflowId
});
}
async showProgress(workflowId) {
const progress = vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: 'Sequential 工作流执行中...',
cancellable: true
}, async (progress, token) => {
const updateProgress = async () => {
const status = await this.client.call('getWorkflowStatus', {
workflowId: workflowId
});
progress.report({
message: `${status.currentStep?.name || '准备中...'}`,
increment: status.progress.percentage - (this.lastProgress || 0)
});
this.lastProgress = status.progress.percentage;
if (status.status === 'completed') {
vscode.window.showInformationMessage('Sequential 工作流完成!');
this.showResults(workflowId);
return;
}
if (status.status === 'failed') {
vscode.window.showErrorMessage('Sequential 工作流失败');
return;
}
// 继续监控
if (!token.isCancellationRequested) {
setTimeout(updateProgress, 2000);
}
};
token.onCancellationRequested(() => {
this.client.call('cancelWorkflow', { workflowId });
});
await updateProgress();
});
}
async showResults(workflowId) {
const report = await this.client.call('generateReport', {
workflowId: workflowId,
format: 'html'
});
// 在新面板中显示报告
const panel = vscode.window.createWebviewPanel(
'sequential-report',
'Sequential 执行报告',
vscode.ViewColumn.One,
{}
);
panel.webview.html = report.content;
}
}相关资源
- Context7 MCP 服务 - 上下文分析服务
- Magic MCP 服务 - AI 代码生成服务
- Playwright MCP 服务 - 自动化测试服务
- MCP 协议文档 - 协议规范
最佳实践
1. 流程设计
- 将复杂任务拆分为独立的步骤
- 明确定义步骤间的依赖关系
- 设计合理的回滚策略
2. 执行监控
- 定期检查流程进度
- 及时处理执行异常
- 保存中间状态用于恢复
3. 结果验证
- 每个步骤都要有验证机制
- 设置质量检查点
- 建立自动化测试
4. 团队协作
- 共享常用的工作流模板
- 建立标准的执行流程
- 定期回顾和优化流程
Sequential - 让复杂任务井然有序