用于安全VB.NET重构的大规模代码平台(MCP)
执行摘要
这 大众码平台(MCP) 是一种分布式、面向服务的架构, 语义安全 VB.NET代码库上的重构。它解决了跨数千个文件自动化代码转换的关键业务需求,这是一项手动或使用交互式IDE工具执行时不切实际且高风险的任务。
主要特点
- 语义保留转换:使用Roslyn的编译器API来确保重构保持代码行为
- 分布式体系结构:面向服务的设计,具有独立的API网关、重构工人和验证工人
- 可扩展插件系统:添加新的重构工具,而无需重新部署平台
- 三条腿的安全保障:
1. 使用Roslyn进行飞行前语义验证 1. 飞行后编译验证 1. 自动化CI/CD测试执行
- 异步作业处理:长时间运行的重构在后台工作器中执行,并具有进度跟踪功能
- 经过实战测试的组件:利用微软的Roslyn、MSBuild和Hangfire实现可靠性
______________________________________________________________________
架构概述
┌─────────────────────────────────────────────────────────────────────┐
│ CLIENT LAYER │
│ (IDE Plugins, CLI Tools, Web Dashboard, CI/CD Pipelines) │
└────────────────────────────────┬────────────────────────────────────┘
│ REST API (HTTPS/JSON)
▼
┌─────────────────────────────────────────────────────────────────────┐
│ API GATEWAY │
│ • REST endpoints (POST /jobs, GET /jobs/{id}) │
│ • Request validation │
│ • Job submission to Hangfire queue │
│ • Lightweight, I/O-bound service │
└────────────────────────────────┬────────────────────────────────────┘
│ Hangfire Job Queue
│ (SQL Server persistent storage)
▼
┌─────────────────────────────────────────────────────────────────────┐
│ REFACTORING WORKER(S) │
│ • Loads VB.NET solutions with MSBuildWorkspace │
│ • Dynamically loads refactoring plugins (AssemblyLoadContext) │
│ • Executes Roslyn transformations │
│ • Writes modified files to disk │
│ • CPU-bound, horizontally scalable │
└────────────────────────────────┬────────────────────────────────────┘
│ Job completion triggers validation
▼
┌─────────────────────────────────────────────────────────────────────┐
│ VALIDATION WORKER(S) │
│ • Git operations (branch, commit, push) │
│ • Programmatic compilation (MSBuild) │
│ • CI/CD integration (Azure DevOps, Jenkins) │
│ • Final verdict: Success or Failure │
└─────────────────────────────────────────────────────────────────────┘设计原理
这 面向服务的体系结构 提供:
- 没有瓶颈:每个服务处理特定的工作负载类型(I/O与CPU)
- 弹性可扩展性:根据队列深度独立扩展工作者
- 容错:单个工作人员故障不会导致整个系统崩溃
- 可维护性:在不重新部署整个系统的情况下更新单个服务
______________________________________________________________________
项目结构
vbdotnet-refactor-mcp/
├── src/
│ ├── MCP.Contracts/ # Plugin interface definitions
│ │ └── IRefactoringProvider.cs
│ ├── MCP.Core/ # Shared models and services
│ │ ├── Models/
│ │ │ ├── RefactoringJobRequest.cs
│ │ │ └── RefactoringJobStatus.cs
│ │ └── Services/
│ │ ├── GitService.cs
│ │ ├── CompilationService.cs
│ │ └── CiCdService.cs
│ ├── MCP.ApiGateway/ # REST API service
│ │ ├── Controllers/RefactoringJobsController.cs
│ │ └── Program.cs
│ ├── MCP.RefactoringWorker/ # Roslyn transformation worker
│ │ ├── Services/RefactoringService.cs
│ │ ├── PluginLoader.cs
│ │ ├── PluginLoadContext.cs
│ │ └── Program.cs
│ ├── MCP.ValidationWorker/ # Git + Compilation + CI/CD worker
│ └── MCP.Plugins.RenameSymbol/ # Example refactoring plugin
│ └── RenameSymbolProvider.cs
├── tests/
│ └── MCP.Tests/
├── docs/
│ └── architecture-blueprint.md # Full architectural specification
├── docker-compose.yml
└── MCP.sln______________________________________________________________________
入门指南
先决条件
- .NET 8.0 SDK 或以后
- SQL Server (适用于Hangfire持久队列)
- Git (用于验证工作流程)
- VB.NET项目 重构
安装
- 克隆存储库:
git clone https://github.com/your-org/vbdotnet-refactor-mcp.git
cd vbdotnet-refactor-mcp- 构建解决方案:
dotnet build MCP.sln- 设置数据库:
# Create the Hangfire database
# Update connection strings in appsettings.json for each service- 部署插件:
# Copy plugin DLLs to the RefactoringWorker plugins directory
mkdir -p src/MCP.RefactoringWorker/plugins
cp src/MCP.Plugins.RenameSymbol/bin/Debug/net8.0/*.dll \
src/MCP.RefactoringWorker/plugins/使用Docker Compose运行
docker-compose up -d这将开始:
- API网关(端口5000)
- 重构工人(后台服务)
- SQL Server(端口1433)
- 航火仪表板(http://localhost:5000/hangfire)
______________________________________________________________________
项目结构概述
此项目使用 结构线 加强项目结构、组织和架构的完整性。
什么是结构化?
Structureline是下一代过梁,旨在加强:
- 文件系统组织:目录深度限制、文件计数约束、命名约定
- 建筑边界:导入图分析和依赖关系规则验证
- 代码质量:死代码检测和测试验证
- CI/CD合规性:GitHub工作流实施
运行结构线
检查项目结构是否符合要求:
structurelint .配置定义见 .structurelint.yml 并执行:
✅ 阶段0-文件系统结构(启用了7条规则):
max-depth: 7-限制目录嵌套max-files-in-dir: 25-每个目录的文件限制(测试为50个)max-subdirs: 15-限制每个目录的子目录naming-convention-PascalCase用于C#,烤肉串case用于YAMLdir-naming-convention-PascalCase for src/和测试/disallowed-patterns-阻止临时文件(.tmp、.bak、.swp、.DS_Store等)- ~~
file-existence~~-禁用(过于严格);手动创建的README - ~~
regex-match~~-已禁用(命名约定足以用于C#)
✅ 第1阶段-架构层实施:
enforce-layer-boundaries: true- 关键特征
- 合同:无依赖关系 - 核心:仅依赖于合同 - 工人/网关:仅依赖于核心+合同 - 插件:仅依赖于合约
⚠️ 第2阶段-死码检测:
- ~~
disallow-orphaned-files~~-已禁用(C#使用.csproj,不导入) - ~~
disallow-unused-exports~~-已禁用(请改用VS代码分析)
✅ 第3阶段-测试验证:
test-location-分别验证测试tests/目录- ~~
test-adjacency~~-已禁用(C#在单独的目录中使用\*Tests.cs模式)
✅ 第4阶段-代码质量度量(基于证据):
max-cognitive-complexity: 15- 新 基于证据(r=0.54与理解时间相关)max-halstead-effort: 100000- 新 神经科学验证(rs=0.901与大脑活动的相关性)
⚠️ 第5阶段-进口模式:
- ~~
disallow-deep-imports~~-已禁用(分析导入;C#使用项目引用)
⚠️ 第6阶段-Linter配置执行:
- ~~
linter-config~~-禁用(尚不支持C#;需要Python/TypeScript/Go/等)
⚠️ 第7阶段-文件内容模板:
- ~~
file-content~~-已禁用(需要自定义C#模板)
📚 创建的文档:
- 根:
README.md,QUICKSTART.md,GITHUB-ACTIONS-GUIDE.md - 组件:6个README包(合约、核心、ApiGateway、重构工作器、验证工作器、插件)
- 测验:
tests/MCP.Tests/README.md - 目录:
src/README.md,tests/README.md,docs/README.md
摘要: 积极执行结构的12条规则+记录架构的10份全面自述文件
安装结构线
如果需要安装structureline:
# Using Go (pinned to specific commit for reproducibility)
go install github.com/Jonathangadeaharder/structurelint/cmd/structurelint@latest
# Or build from source (recommended for development)
git clone https://github.com/Jonathangadeaharder/structurelint.git
cd structurelint
go build -o structurelint ./cmd/structurelint
sudo cp structurelint /usr/local/bin/CI/CD集成
Structureline已经集成到GitHub Actions工作流中(.github/workflows/test-and-log.yml).它在每次推送时自动运行,以验证项目结构。
要添加到其他工作流,请执行以下操作:
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.21'
- name: Install structurelint
run: |
git clone https://github.com/Jonathangadeaharder/structurelint.git /tmp/structurelint
cd /tmp/structurelint
go build -o /usr/local/bin/structurelint ./cmd/structurelint
- name: Run Structurelint
run: structurelint .______________________________________________________________________
用法
提交重构作业
发布 http://localhost:5000/api/v1/refactoringjobs
{
"solutionPath": "/path/to/MyLegacyApp.sln",
"refactoringToolName": "RenameSymbol",
"parameters": {
"targetFile": "MyProject/MyClass.vb",
"textSpanStart": 150,
"textSpanLength": 12,
"newName": "MyRenamedMethod",
"includeCommentsAndStrings": true
},
"validationPolicy": {
"onSuccess": "CreatePullRequest",
"onFailure": "DeleteBranch",
"steps": ["Compile", "Test"]
},
"ciPipelineTrigger": {
"type": "AzureDevOps",
"pipelineId": "123",
"apiEndpoint": "https://dev.azure.com/myorg/myproject",
"authToken": "your-pat-token"
}
}响应: 202 Accepted
{
"jobId": "abc-123-def",
"status": "Accepted",
"message": "Job has been accepted and queued for processing",
"statusUrl": "http://localhost:5000/api/v1/refactoringjobs/abc-123-def"
}轮询作业状态
获取 http://localhost:5000/api/v1/refactoringjobs/{jobId}
{
"jobId": "abc-123-def",
"status": "Succeeded",
"message": "Refactoring completed successfully. Modified 15 file(s).",
"resultUrl": "https://github.com/myorg/myrepo/pull/456",
"createdAt": "2025-01-15T10:30:00Z",
"updatedAt": "2025-01-15T10:35:00Z",
"executionLog": [
"[10:30:05] Job started",
"[10:30:10] Solution loaded. Projects: 12",
"[10:32:00] Refactoring transformation completed",
"[10:33:15] Build succeeded",
"[10:35:00] All tests passed"
]
}______________________________________________________________________
“三脚凳”的安全保障
每个重构作业都会经历一个三阶段的验证流程,以确保 语义保存:
第一阶段:飞行前语义验证
技术:罗斯林的 Renamer API,具有冲突检测和 SpeculativeSemanticModel
目的:检测命名冲突和语义更改 *之前* 修改文件
示例:如果重命名 DoWork 会与现有的 DoWork 过载,作业立即失败
第二阶段:飞行后编辑
技术:MSBuild BuildManager API
目的:验证转换后的代码是否编译正确
结果:如果编译失败,重构会引入语法或类型错误。作业失败,分支已删除。
第三阶段:飞行后测试执行
技术:CI/CD集成(Azure DevOps、Jenkins)
目的:执行项目现有的测试套件,以验证行为的正确性
结果:如果测试失败,重构会改变程序行为。作业失败,分支已删除。
______________________________________________________________________
创建自定义重构插件
步骤1:创建新的类库
dotnet new classlib -n MCP.Plugins.ExtractMethod
dotnet add reference ../../MCP.Contracts/MCP.Contracts.csproj
dotnet add package Microsoft.CodeAnalysis.VisualBasic.Workspaces第二步:实施 IRefactoringProvider
using MCP.Contracts;
using Microsoft.CodeAnalysis;
public class ExtractMethodProvider : IRefactoringProvider
{
public string Name => "ExtractMethod";
public string Description => "Extracts selected code into a new method";
public ValidationResult ValidateParameters(JsonElement parameters)
{
// Validate required parameters
if (!parameters.TryGetProperty("targetFile", out _))
return ValidationResult.Failure("Missing 'targetFile' parameter");
return ValidationResult.Success();
}
public async Task ExecuteAsync(RefactoringContext context)
{
// 1. Load document and get semantic model
// 2. Find the target syntax node
// 3. Use SpeculativeSemanticModel for pre-flight validation
// 4. Transform the syntax tree
// 5. Return the new solution
return RefactoringResult.Success(transformedSolution);
}
}步骤3:部署插件
dotnet build MCP.Plugins.ExtractMethod
cp bin/Debug/net8.0/*.dll ../MCP.RefactoringWorker/plugins/RefactoringWorker将在启动时自动发现并加载新插件。
______________________________________________________________________
配置
API网关(appsettings.json)
{
"ConnectionStrings": {
"HangfireConnection": "Data Source=localhost;Initial Catalog=MCPHangfire;..."
}
}重构工人(appsettings.json)
{
"Hangfire": {
"WorkerCount": 4
},
"PluginDirectory": "plugins",
"ConnectionStrings": {
"HangfireConnection": "..."
}
}______________________________________________________________________
监测和可观察性
航火仪表板
访问作业队列仪表板: http://localhost:5000/hangfire
- 查看待处理、正在运行和已完成的作业
- 查看作业执行历史记录并重试
- 监控工人健康状况
应用程序日志
所有服务都使用结构化日志记录 Microsoft.Extensions.Logging.在中配置日志级别 appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"MCP": "Debug"
}
}
}______________________________________________________________________
可扩展性
水平缩放
- API网关:无状态,可以在负载均衡器后运行多个实例
- 重构工人:根据CPU使用率和队列深度进行扩展
- 验证工作人员:根据编译和CI/CD工作量进行扩展
推荐部署
- 小团队 (少于50名开发人员):1个API网关,2个重构工人
- 中型团队 (50-200名开发人员):2个API网关,4-8名重构工人
- 大型团队 (200多名开发人员):具有自动扩展策略的Kubernetes
______________________________________________________________________
安全考虑
认证
- 为API网关实现OAuth 2.0或API密钥
- 对所有外部通信使用HTTPS
- 将CI/CD令牌存储在Azure密钥库或类似库中
输入验证
- 必须验证解决方案路径(无目录遍历)
- 插件加载使用AssemblyLoadContext隔离来防止恶意代码执行
审计日志
- 所有提交和完成的工作都会被记录下来
- Git提交包括MCP服务帐户归因
______________________________________________________________________
故障排除
常见问题
问题:“已加载解决方案,但不包含任何项目”
解决方案:确保 Microsoft.CodeAnalysis.VisualBasic.Workspaces 存在并且MSBuild已正确注册
问题:“未找到插件”
解决方案:验证插件DLL是否在 plugins 目录和工具 IRefactoringProvider
问题:“重构后编译失败”
解决方案:这表示Roslyn转换错误。查看执行日志以了解特定的编译错误。
______________________________________________________________________
贡献
- 分叉存储库
- 创建要素分支(
git checkout -b feature/my-new-tool) - 按照插件指南实现重构插件
- 添加单元测试
- 提交拉取请求
______________________________________________________________________
参考文献
______________________________________________________________________
许可证
版权所有©2025。保留所有权利。
本项目实施随附蓝图文件中规定的建筑设计。它展示了一种在企业规模上安全、自动化的代码重构的生产就绪方法。
