.NET静态分析DotnetStaticAnalysisMcp。服务器
一个强大的模型上下文协议(MCP)服务器,为提供实时静态分析。NET解决方案。此服务器与MCP兼容的聊天客户端集成,直接在您的对话界面中提供全面的代码分析、编译错误检测和项目见解。
特性
核心分析能力
- 🔍 分析:加载并分析整个。NET解决方案,包含详细的项目信息
- ⚠️ 编译错误检测:通过精确的行和列位置识别编译错误
- 📊 项目见解:获取全面的项目元数据、依赖关系和源文件信息
- 🛠️ 诊断工具:用于故障排除的环境和MSBuild状态检查
- 📝 结构化日志记录:JSON格式的全面日志记录,用于调试和监控
- 🔄 实时更新:在开发过程中支持热重载
dotnet watch
高级类型分析和重构支持
- 🔍 类型使用情况发现:查找整个解决方案中所有类型的引用
- 🔗 会员使用情况分析:跟踪方法、属性、字段和事件使用情况
- 📋 相关性分析:了解类型依赖关系和关系
- 🔧 安全重构验证:检查重命名安全性并预览影响
- ⚡ 影响范围分析:在修改之前分析潜在的突破性变化
- 🎯 跨项目分析:处理解决方案中多个项目的引用
快速开始
先决条件
- .NET 9.0 SDK或更高版本
- MCP兼容的聊天客户端(Claude Desktop、Cline等)
安装
- 克隆存储库:
git clone MCP
cd MCP- 构建服务器:
dotnet build DotnetStaticAnalysisMcp.Server- 配置您的MCP客户端 通过将以下内容添加到MCP配置文件中:
用于开发(带热重载):
{
"mcpServers": {
"dotnet-analysis": {
"command": "dotnet",
"args": ["watch", "run", "--project", "/path/to/MCP/DotnetStaticAnalysisMcp.Server"],
"env": {}
}
}
}用于生产:
{
"mcpServers": {
"dotnet-analysis": {
"command": "dotnet",
"args": ["run", "--project", "/path/to/MCP/DotnetStaticAnalysisMcp.Server"],
"env": {}
}
}
}- 重新启动MCP客户端 加载服务器
用法
配置后,您可以在MCP兼容聊天中使用这些命令:
岩心分析命令
加载解决方案
Load the solution at /path/to/your/solution.sln使用 load_solution 用于分析a的工具。NET解决方案文件。
获取解决方案信息
Show me the structure of the loaded solution使用 get_solution_info 显示项目、依赖关系和元数据的工具。
检查编译错误
Are there any compilation errors in the current solution?使用 get_compilation_errors 用于查找和报告所有编译问题的工具。
分析特定文件
Analyze the file Program.cs for errors使用 analyze_file 用于检查特定文件是否存在编译问题的工具。
诊断命令
检查服务器状态
What's the current status of the .NET analysis server?使用诊断工具显示服务器运行状况、MSBuild状态和环境信息。
获取代码建议
Give me code improvement suggestions for performance and style使用 get_code_suggestions 该工具提供AI驱动的代码改进。
可用的MCP工具
| 工具 | 说明 | 参数 |
|---|---|---|
load_solution | 加载a。NET解决方案文件 | solutionPath (字符串) |
get_solution_info | 获取详细的解决方案结构 | 无 |
get_compilation_errors | 查找编译错误和警告 | 无 |
analyze_file | 分析特定文件 | filePath (字符串) |
get_code_suggestions | 获得AI驱动的代码改进 | categories, minimumPriority, maxSuggestions |
get_suggestion_categories | 列出可用的建议类别 | 无 |
get_server_version | 获取服务器版本和构建信息 | 无 |
get_basic_diagnostics | 获取环境诊断 | 无 |
类型分析和重构工具
| 工具 | 说明 | 参数 |
|---|---|---|
find_type_usages | 查找特定类型的所有引用 | typeName, includeDocumentation, maxResults |
find_member_usages | 查找对类型成员的所有引用 | typeName, memberName |
find_namespace_usages | 查找命名空间使用情况和导入 | namespaceName |
get_type_dependencies | 获取类型所依赖的类型 | typeName |
get_type_dependents | 获取依赖于某个类型的类型 | typeName |
analyze_impact_scope | 分析变更的潜在影响 | typeName |
validate_rename_safety | 检查重命名是否会导致冲突 | currentName, proposedName |
preview_rename_impact | 预览受重命名影响的文件 | currentName, proposedName |
get_type_analysis_summary | 完整的类型分析报告 | typeName |
配置文件
MCP客户端配置位置
- 克劳德桌面:
~/.config/claude/claude_desktop_config.json - 克莱恩:通常在VS代码设置中或
.cline/config.json - 其他MCP客户端:检查他们的文件
完整配置示例
{
"mcpServers": {
"dotnet-analysis": {
"command": "dotnet",
"args": ["watch", "run", "--project", "/home/user/projects/MCP/DotnetStaticAnalysisMcp.Server"],
"env": {
"DOTNET_CLI_TELEMETRY_OPTOUT": "1"
}
}
}
}日志记录和调试
服务器提供全面的日志记录以进行故障排除:
日志文件
- 结构化日志:
~/.mcp/logs/dotnet-analysis*.log(JSON格式) - 调试日志:
/tmp/mcp-debug-*.log(简单文本格式)
查看日志
# View recent structured logs
tail -f ~/.mcp/logs/dotnet-analysis$(date +%Y%m%d).log | jq
# View debug logs
tail -f /tmp/mcp-debug-$(date +%Y%m%d).log常见问题
服务器未启动
- 检查一下。NET 9.0 SDK已安装:
dotnet --version - 验证MCP配置中的项目路径
- 检查MCP客户端日志中的错误消息
未检测到项目
- 确保解决方案文件存在且有效
- 检查MSBuild是否已正确安装
- 使用诊断工具检查MSBuild状态
未发现编译错误
- 首先验证解决方案是否成功加载
- 检查项目是否使用受支持的。NET版本
- 确保所有NuGet包都已还原:
dotnet restore
发展
项目结构
MCP/
├── DotnetStaticAnalysisMcp.Server/ # Main MCP server application
│ ├── Models/ # Data models for analysis results
│ ├── Services/ # Core analysis and MCP services
│ └── Program.cs # Server entry point
├── MCP.Tests/ # Unit and integration tests
├── MCP.IntegrationTests/ # Integration tests
├── MCP.TestProject/ # Test project with deliberate errors
└── README.md # This file从源头构建
# Restore dependencies
dotnet restore
# Build all projects
dotnet build
# Run tests
dotnet test
# Run the server locally
dotnet run --project DotnetStaticAnalysisMcp.Server运行测试
# Run all tests
dotnet test
# Run specific test project
dotnet test MCP.IntegrationTests
# Run with verbose output
dotnet test --verbosity normal贡献
- 分叉存储库
- 创建要素分支:
git checkout -b feature/amazing-feature - 进行更改并添加测试
- 确保所有测试通过:
dotnet test - 提交您的更改:
git commit -m 'Add amazing feature' - 推到分支:
git push origin feature/amazing-feature - 打开拉取请求
许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
支持
- 问题:在GitHub Issues上报告错误和请求功能
- 讨论:加入GitHub讨论中的对话
- 文档:查看wiki以获取其他文档
示例使用场景
场景1:代码审查助手
Load the solution at /home/user/MyProject/MyProject.sln and check for any compilation errors. Then analyze the main Program.cs file and suggest performance improvements.场景2:项目健康检查
What's the current status of the loaded solution? Show me the project structure and any issues that need attention.场景3:调试构建问题
I'm getting build errors. Can you load my solution and tell me exactly what's wrong and where?场景4:代码质量分析
场景5:类型使用分析
Find all usages of the Customer class and analyze its dependencies to understand the impact of potential changes.场景6:安全重构
I want to rename the Order class to PurchaseOrder. Check if this is safe and show me what would be affected.场景7:依赖性分析
Show me all the types that depend on the ICustomer interface and what types it depends on.场景8:会员使用情况跟踪
Find all places where the AddOrder method is called and analyze the impact of changing its signature.Give me code suggestions for style and best practices improvements with high priority items first.高级配置
环境变量
您可以使用环境变量自定义服务器行为:
{
"mcpServers": {
"dotnet-analysis": {
"command": "dotnet",
"args": ["run", "--project", "/path/to/MCP/DotnetStaticAnalysisMcp.Server"],
"env": {
"DOTNET_CLI_TELEMETRY_OPTOUT": "1",
"MSBUILD_EXE_PATH": "/custom/path/to/msbuild",
"DOTNET_ROOT": "/custom/dotnet/root"
}
}
}
}性能调整
对于大型解决方案,您可能需要调整这些设置:
- 记忆:增加的可用内存。NET进程
- 超时:调整超大代码库的解决方案加载超时
- 日志记录:减少生产中的日志记录冗长
安全考虑
- 服务器以与MCP客户端相同的权限运行
- 仅加载来自可信来源的解决方案
- 在分析具有自定义MSBuild目标的解决方案时要小心
故障排除指南
问题:“未找到MSBuild”
解决方案:
- 安装。NET SDK(不仅仅是运行时)
- 确保
dotnet在你的路径中 - 试着跑步
dotnet --info验证安装
问题:“解决方案加载但显示0个项目”
解决方案:
- 检查解决方案文件是否有效
- 确保所有引用的项目都存在
- 跑
dotnet restore关于解决方案 - 检查MSBuild错误的诊断日志
问题:“服务器没有响应”
解决方案:
- 检查MCP客户端日志中的连接错误
- 验证服务器进程是否正在运行
- 尝试重新启动MCP客户端
- 检查防火墙/防病毒阻止进程
问题:“未检测到编译错误”
解决方案:
- 确保首先成功加载解决方案
- 检查项目是否支持目标。NET版本
- 验证所有NuGet包是否已还原
- 尝试手动构建解决方案
dotnet build
api参考
响应格式
所有MCP工具都返回具有以下通用结构的JSON响应:
{
"success": true,
"timestamp": "2024-12-20T15:30:00Z",
"data": { /* tool-specific data */ }
}错误处理
当发生错误时,响应包括详细的错误信息:
{
"success": false,
"error": "Error message",
"error_code": "ERROR_CODE",
"timestamp": "2024-12-20T15:30:00Z",
"details": { /* additional error context */ }
}致谢
高级类型分析和重构支持
这个。NET静态分析DotnetStaticAnalysisMcp。服务器现在包括全面的类型使用分析和重构支持,使AI代理能够在充分理解代码库结构和依赖关系的情况下安全地执行复杂的代码转换。
🔍 类型使用情况发现工具
find_type_usages -查找所有类型引用
在整个解决方案中查找对特定类型(类、接口、结构、枚举)的所有引用。
参数:
typeName(string):要查找的类型的名称(例如,“Customer”或“MyNamespace.Customer”)includeDocumentation(bool):包含XML文档引用(默认值:true)maxResults(int):返回的最大结果数(默认值:100)
检测到的使用类型:
- 变量声明和实例化
- 方法参数和返回类型
- 泛型类型参数
- 基类和实现的接口
- 属性用法
- 铸造操作和类型检查
- 使用指令
- XML文档参考
例子:
find_type_usages typeName="Customer" includeDocumentation=true maxResults=50find_member_usages -查找会员推荐
查找对特定类型成员(方法、属性、字段、事件)的所有引用。
参数:
typeName(string):包含类型名称memberName(string):要查找的成员名称
成员使用类型:
- 方法调用和属性访问
- 现场访问和分配
- 活动订阅/取消订阅
- 方法重写和实现
例子:
find_member_usages typeName="Customer" memberName="AddOrder"find_namespace_usages -查找命名空间引用
查找所有using语句和对命名空间的完全限定引用。
参数:
namespaceName(string):要查找的命名空间(例如,“System.Collections.Generic”)
例子:
find_namespace_usages namespaceName="MyProject.Models"📊 依赖性分析工具
get_type_dependencies -分析类型依赖关系
获取特定类型所依赖的所有类型。
分析的依赖关系类型:
- 继承关系(基类)
- 接口实现
- 组合关系(属性、字段)
- 方法参数依赖关系
- 通用约束
- 属性依赖度
例子:
get_type_dependencies typeName="Customer"get_type_dependents -反向依赖性分析
获取依赖于特定类型的所有类型。
例子:
get_type_dependents typeName="Customer"⚡ 影响分析工具
analyze_impact_scope -分析变更影响
分析更改类型的潜在影响(会破坏什么)。
影响范围:
None:未找到用法SameFile:影响仅限于单个文件SameProject:对一个项目的影响MultipleProjects:对多个项目的影响EntireSolution:对整个解决方案的影响
提供:
- 受影响项目列表
- 潜在的突破性变化
- 安全更改建议
例子:
analyze_impact_scope typeName="Customer"🔧 安全重构验证工具
validate_rename_safety -检查重命名安全
检查重命名类型/成员是否会导致冲突或破坏更改。
参数:
currentName(string):类型的当前名称proposedName(string):建议的新名称
验证:
- 名称与现有类型冲突
- 可访问性限制
- 跨项目影响
例子:
validate_rename_safety currentName="Customer" proposedName="CustomerEntity"preview_rename_impact -预览重命名更改
准确显示重命名操作会影响哪些文件和行。
提供:
- 精确的文件位置(路径、行、列)
- 显示上下文的代码片段
- 按项目细分
例子:
preview_rename_impact currentName="Customer" proposedName="CustomerEntity"🎯 综合分析工具
get_type_analysis_summary -完成类型分析
在一次调用中获取全面的类型分析信息,包括用法、依赖关系和影响。
包括:
- 整个解决方案中的所有类型用法
- 依赖性分析(双向)
- 影响范围评估
- 汇总统计
例子:
get_type_analysis_summary typeName="Customer"类型分析响应格式
类型使用参考
{
"filePath": "/path/to/file.cs",
"projectName": "MyProject",
"startLine": 15,
"startColumn": 8,
"endLine": 15,
"endColumn": 16,
"usageKind": "Declaration",
"context": "Class: CustomerService",
"codeSnippet": "Customer customer = new Customer();",
"containingMember": "CreateCustomer",
"containingType": "CustomerService"
}使用类型
Declaration:类型声明(类、接口等)Instantiation:对象创建(new Customer())MethodParameter:方法参数类型MethodReturnType:方法返回类型PropertyType:属性类型声明FieldType:字段类型声明GenericTypeArgument:泛型类型参数BaseClass:继承关系ImplementedInterface:接口实现AttributeUsage:属性应用程序CastOperation:类型铸造TypeOfExpression:typeof(Customer)IsExpression:obj is CustomerAsExpression:obj as CustomerUsingDirective:using MyNamespace;XmlDocumentation:XML文档引用
依赖性分析响应
{
"success": true,
"analyzedType": "Customer",
"dependencies": [
{
"dependentType": "Customer",
"dependencyType": "Address",
"kind": "Composition",
"context": "Property: Address"
}
],
"totalDependencies": 5,
"totalDependents": 3
}高级使用示例
场景1:安全类型重命名
# 1. Check if rename is safe
validate_rename_safety currentName="Customer" proposedName="ClientEntity"
# 2. Preview the impact
preview_rename_impact currentName="Customer" proposedName="ClientEntity"
# 3. Analyze full scope
analyze_impact_scope typeName="Customer"场景2:理解类型依赖关系
# 1. Get complete analysis
get_type_analysis_summary typeName="Order"
# 2. Find what depends on Order
get_type_dependents typeName="Order"
# 3. Find what Order depends on
get_type_dependencies typeName="Order"场景3:重构准备
# 1. Find all usages of a method
find_member_usages typeName="Customer" memberName="CalculateTotal"
# 2. Analyze impact of changing the method
analyze_impact_scope typeName="Customer"
# 3. Check namespace usage
find_namespace_usages namespaceName="MyProject.Services"技术实现
罗斯林集成
- 使用Microsoft。语义分析的代码分析
- 利用SymbolFinder进行精确的参考检测
- 支持解决方案中的跨项目分析
- 处理泛型类型、嵌套类型和分部类
性能优化
- 高效的符号查找和缓存
- 可配置的结果限制
- 跨项目的并行分析
- 内存高效的参考跟踪
错误处理
- 妥善处理缺失类型
- 清除无效操作的错误消息
- 对部分编译的解决方案的稳健处理
- 用于调试的全面日志记录
类型分析架构图
graph TB
subgraph "MCP Client (AI Agent)"
A[AI Agent Request]
end
subgraph "DotnetStaticAnalysisMcp.Server"
B[MCP Tools Layer]
C[RoslynAnalysisService]
D[Type Analysis Engine]
end
subgraph "Analysis Capabilities"
E[Type Usage Discovery]
F[Member Usage Analysis]
G[Dependency Analysis]
H[Impact Assessment]
I[Refactoring Validation]
end
subgraph "Roslyn Integration"
J[Semantic Model]
K[Symbol Finder]
L[Syntax Analysis]
M[Cross-Project References]
end
subgraph ".NET Solution"
N[Project 1]
O[Project 2]
P[Project N]
Q[Source Files]
R[References]
end
A --> B
B --> C
C --> D
D --> E
D --> F
D --> G
D --> H
D --> I
E --> J
F --> K
G --> L
H --> M
I --> J
J --> N
K --> O
L --> P
M --> Q
J --> R类型使用分析流程
sequenceDiagram
participant AI as AI Agent
participant MCP as DotnetStaticAnalysisMcp.Server
participant Roslyn as Roslyn Engine
participant Solution as .NET Solution
AI->>MCP: find_type_usages("Customer")
MCP->>Roslyn: FindTypeSymbol("Customer")
Roslyn->>Solution: Search across projects
Solution-->>Roslyn: Type symbol found
Roslyn->>Solution: FindReferencesAsync(symbol)
Solution-->>Roslyn: All reference locations
Roslyn->>MCP: Analyze usage contexts
MCP->>MCP: Categorize usage kinds
MCP->>MCP: Generate structured response
MCP-->>AI: TypeUsageAnalysisResult依赖性分析可视化
graph LR
subgraph "Customer Dependencies"
Customer --> ICustomer[ICustomer Interface]
Customer --> Address[Address Class]
Customer --> Order[Order Collection]
Customer --> PropertyChangedEventArgs[PropertyChangedEventArgs]
end
subgraph "Customer Dependents"
CustomerService --> Customer
OrderService --> Customer
CustomerController --> Customer
CustomerValidator --> Customer
end
subgraph "Usage Types"
Customer -.->|Declaration| CD[Class Declaration]
Customer -.->|Instantiation| CI[new Customer]
Customer -.->|Parameter| CP[Method Parameters]
Customer -.->|Return Type| CR[Return Types]
Customer -.->|Property| CProp[Property Types]
Customer -.->|Inheritance| CInher[Base Classes]
Customer -.->|Interface| CInt[Interfaces]
end重构安全分析
flowchart TD
A[Rename Request: Customer → ClientEntity] --> B{Type Exists?}
B -->|Yes| C[❌ Conflict Detected]
B -->|No| D[Find All Usages]
D --> E[Analyze Usage Contexts]
E --> F{Cross-Project Impact?}
F -->|Yes| G[⚠️ Multi-Project Impact]
F -->|No| H[✅ Safe to Rename]
G --> I[Generate Warnings]
H --> J[Generate Preview]
C --> K[Return Conflicts]
I --> L[Return Impact Analysis]
J --> L
K --> L
L --> M[Present to AI Agent]