使用说明
SE333最终项目——MCP服务器
基于Python 模型上下文协议(MCP)服务器 提供自动化代码质量分析和测试分析工具,使用 fastmcp 通过SSE运输。
存储库: github.com/ghaaccount409-school/final_project_se333_NigelMaloney
目录
概述
此MCP服务器公开了六个代码质量分析工具,这些工具与中描述的工作流相一致 tester.prompt.md 和 codereview.prompt.md所有工具都可以通过HTTP/SSE由任何兼容MCP的客户端(VS Code、Claude Desktop等)调用。
技术栈:
| 组件 | 版本 |
|---|---|
| Python | 3.14.0 |
| fastmcp/mcp | 3.1.0+/1.26.0+ |
| 运输 | 苏格兰和南方能源公司(http://127.0.0.1:8000/sse) |
| 测试运行器 | pytest 9.0+,带pytest cov |
安装和设置
先决条件
- Python 3.14+
uv包管理器
步骤
# 1. Clone the repository
git clone https://github.com/ghaccount409-school/final_project_se333_NigelMaloney.git
cd final_project_se333_NigelMaloney
cd CodeBase
# 2. Install dependencies (creates .venv automatically)
uv sync
# 3. Install dev dependencies (pytest, pytest-cov)
uv add pytest pytest-cov --dev
# 4. Start the server
uv run python main.py
服务器启动于 http://127.0.0.1:8000。您应该看到:
INFO: Started server process [XXXXX]
INFO: Waiting for application startup.
INFO: Application startup complete.
配置
VS代码(mcp.json)
添加以下内容 %APPDATA%\Code\User\mcp.json (Windows)或 ~/.config/Code/User/mcp.json (macOS/Linux):
{
"servers": {
"se333-MCP-server": {
"url": "http://127.0.0.1:8000/sse",
"type": "http"
}
}
}
克劳德桌面版
{
"mcpServers": {
"se333-server": {
"command": "uv",
"args": ["run", "python", "/absolute/path/to/final_project_se333_NigelMaloney/CodeBase/main.py"]
}
}
}
服务器默认值
| 设置 | 默认值 | 注释 |
|---|---|---|
| 主持人 | 127.0.0.1 |
仅环回-不暴露于网络 |
| 港口 | 8000 |
变化 fastmcp 如果需要 |
| 运输 | sse |
VS Code HTTP类型连接需要 |
运行提示工作流
此存储库包括从Copilot Chat使用的提示文件:
.github/prompts/tester.prompt.md.github/prompts/codereview.prompt.md
在Copilot聊天中使用以下命令:
运行测试人员工作流程
#file:.github/prompts/tester.prompt.md <github-repo-to-test> <user-repo-to-push>
例子:
#file:.github/prompts/tester.prompt.md https://github.com/spring-projects/spring-petclinic https://github.com/ghaccount409-school/se333-demo
这与测试仪提示指令模式相匹配:
#file:./tester.prompt.md <github-repo-to-test> <user-repo-to-push>
运行代码审查工作流
#file:.github/prompts/codereview.prompt.md
当前 codereview.prompt.md 其指令中不需要位置存储库参数。
MCP工具参考
analyze_coverage
来源: tester.prompt.md --步骤5(解析Jacoco/覆盖率输出并识别差距)
评估代码覆盖率,并返回带有建议的结构化状态。
参数:
| 名称 | 类型 | 描述 |
|---|---|---|
covered_lines |
int |
测试覆盖的线路 |
total_lines |
int |
代码库中的总行数 |
退货: dict
| 密钥 | 类型 | 描述 |
|---|---|---|
coverage |
float |
四舍五入到小数点后两位的百分比 |
covered_lines |
int |
输入回声 |
total_lines |
int |
输入回声 |
status |
str |
"excellent" |
recommendation |
str |
人类可读指南 |
状态阈值:
| 状态 | 条件 |
|---|---|
excellent |
100% |
good |
≥ 90% |
acceptable |
≥ 70% |
poor |
< 70% |
error |
total_lines == 0 |
例子:
analyze_coverage(covered_lines=95, total_lines=100)
# → {"coverage": 95.0, "status": "good", "recommendation": "High coverage. Consider testing edge cases.", ...}
generate_test_report
来源: tester.prompt.md --步骤2-3(运行测试,解释结果)
从原始测试执行计数器生成摘要报告。
参数:
| 名称 | 类型 | 描述 |
|---|---|---|
total_tests |
int |
已执行的测试总数 |
passed_tests |
int |
通过的测试 |
failed_tests |
int |
失败的测试 |
skipped_tests |
int |
跳过的测试 |
退货: dict
| 密钥 | 类型 | 描述 |
|---|---|---|
summary |
dict |
原始计数(total, passed, failed, skipped) |
metrics |
dict |
pass_rate, failure_rate, skip_rate (百分比) |
status |
str |
"passed" |
action |
str |
建议下一步 |
例子:
generate_test_report(total_tests=37, passed_tests=37, failed_tests=0, skipped_tests=0)
# → {"status": "passed", "metrics": {"pass_rate": 100.0, ...}, "action": "All tests passed. Ready for deployment."}
detect_code_smells
来源: codereview.prompt.md --代码气味检测和重构建议
识别常见代码质量反模式的存在。
参数:
| 名称 | 类型 | 描述 |
|---|---|---|
has_duplicates |
bool |
检测到代码重复 |
has_long_functions |
bool |
函数超出建议长度 |
has_unused_vars |
bool |
存在未使用的变量或导入 |
退货: dict
| 密钥 | 类型 | 描述 |
|---|---|---|
detected_smells |
int |
发现的气味数量 |
smells |
list[str] |
标识符: "code_duplication", "long_functions", "unused_variables" |
severity |
str |
"low" |
refactoring_suggestions |
list[str] |
每种气味一个建议 |
priority |
str |
"soon" (0-1气味) |
严重性逻辑: high 如果气味≥2, medium 如果恰好为1, low 如果没有。
例子:
detect_code_smells(has_duplicates=True, has_long_functions=True, has_unused_vars=False)
# → {"detected_smells": 2, "severity": "high", "priority": "immediate", ...}
scan_security_risks
来源: codereview.prompt.md --安全漏洞扫描(CodeQL等效检查)
检查三个具有CWE引用和补救步骤的高影响漏洞类别。
参数:
| 名称 | 类型 | 描述 |
|---|---|---|
has_sql_injection |
bool |
存在SQL注入风险 |
has_hardcoded_secrets |
bool |
源代码中硬编码的凭据/令牌 |
has_weak_crypto |
bool |
使用的加密算法较弱或已弃用 |
退货: dict
| 密钥 | 类型 | 描述 |
|---|---|---|
vulnerabilities_found |
int |
检测到的漏洞计数 |
vulnerabilities |
list[dict] |
每个条目都有 type, cve (CWE-ID), remediation |
risk_level |
str |
"low" |
action_required |
bool |
True 如果发现任何漏洞 |
风险等级逻辑: SQL注入→ "critical" (优先)。秘密或弱加密→ "high" 如果没有SQL注入。
漏洞参考表:
| 类型 | CWE | 补救 |
|---|---|---|
SQL_INJECTION |
CWE-89 | 使用参数化查询/ORM |
HARDCODED_CREDENTIALS |
CWE-798 | 移动到环境变量或秘密库 |
WEAK_CRYPTOGRAPHY |
CWE-327 | 使用 hashlib / cryptography 使用现代算法 |
例子:
scan_security_risks(has_sql_injection=False, has_hardcoded_secrets=True, has_weak_crypto=False)
# → {"vulnerabilities_found": 1, "risk_level": "high", "action_required": True, ...}
enforce_style_guide
来源: codereview.prompt.md --使用自动修复指导执行样式指南
检查三个PEP 8/样式指南标准,并返回数字合规性得分。
参数:
| 名称 | 类型 | 描述 |
|---|---|---|
uses_consistent_naming |
bool |
命名约定是一致的(snake_case、PascalCase) |
follows_pep8 |
bool |
代码符合PEP 8标准 |
has_docstrings |
bool |
公共函数和类有文档记录 |
退货: dict
| 密钥 | 类型 | 描述 |
|---|---|---|
violations |
int |
违规次数(0-3) |
details |
list[dict] |
每个条目都有 rule, severity, fix |
style_score |
int |
100 − (violations × 25) |
compliant |
bool |
True 只有当 violations == 0 |
每条规则的严重性:
| 规则 | 严重性 |
|---|---|
naming_convention |
"warning" |
pep8_compliance |
"error" |
documentation |
"warning" |
例子:
enforce_style_guide(uses_consistent_naming=True, follows_pep8=False, has_docstrings=True)
# → {"violations": 1, "style_score": 75, "compliant": False, "details": [{"rule": "pep8_compliance", ...}]}
check_complexity
来源: codereview.prompt.md --静态分析/复杂性度量(类似于SpotBugs/PMD输出)
对McCabe圈复杂度进行分类,并计算密度度量。
参数:
| 名称 | 类型 | 描述 |
|---|---|---|
cyclomatic_complexity |
int |
代码单元的McCabe复杂性得分 |
lines_of_code |
int |
分析单元中的线路总数 |
退货: dict
| 密钥 | 类型 | 描述 |
|---|---|---|
cyclomatic_complexity |
int |
输入回声 |
lines_of_code |
int |
输入回声 |
complexity_level |
str |
"low" |
density |
float |
complexity / lines_of_code (四舍五入到3dp) |
recommendation |
str |
基于级别的指导 |
needs_refactoring |
bool |
True 当水平为 "high" |
分类阈值:
| 级别 | 条件 |
|---|---|
low |
≤ 5 |
moderate |
6–10 |
high |
> 10 |
例子:
check_complexity(cyclomatic_complexity=12, lines_of_code=80)
# → {"complexity_level": "high", "density": 0.15, "needs_refactoring": True, ...}
测试
# from repository root:
# cd final_project_se333_NigelMaloney/CodeBase
# Run all tests
uv run pytest test_main.py -v
# Run with coverage report
uv run pytest test_main.py --cov=main --cov-report=term-missing
# Run a specific test class
uv run pytest test_main.py::TestScanSecurityRisks -v
测试套件摘要(37个测试,100%覆盖率):
| 课程 | 测试 | 涵盖的工具 |
|---|---|---|
TestAnalyzeCoverage |
6 | analyze_coverage |
TestGenerateTestReport |
6 | generate_test_report |
TestDetectCodeSmells |
6 | detect_code_smells |
TestScanSecurityRisks |
6 | scan_security_risks |
TestEnforceStyleGuide |
6 | enforce_style_guide |
TestCheckComplexity |
6 | check_complexity |
TestMainEntrypoint |
1 | 服务器启动 |
故障排除和常见问题
安装
Q No module named 'mcp' 或 No module named 'fastmcp'
跑 uv sync 从 CodeBase 安装所有声明的依赖项的目录。如果 uv 不在您的路径上,请将其定位在 ~/.local/bin/uv (macOS/Linux)或 %USERPROFILE%\.local\bin\uv.exe (Windows)。
Q Python 3.14 not found 或 requires-python >=3.14
检查您的版本 python --version如果低于3.14,请通过安装 python.org 或 pyenv:
pyenv install 3.14.0
pyenv local 3.14.0
cd CodeBase
uv sync
Q: Windows上的虚拟环境激活失败
# PowerShell (may require execution policy change)
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
.\.venv\Scripts\Activate.ps1
或使用 uv run 直接避免手动激活。
运行时
Q OSError: [Errno 10048] / Address already in use 在8000端口
另一个进程正在使用端口8000(可能是之前的服务器实例)。
# Windows — find and kill the process
Get-Process -Id (Get-NetTCPConnection -LocalPort 8000).OwningProcess | Stop-Process
Q: VS Code无法发现MCP工具
- 确认服务器正在运行:打开浏览器
http://127.0.0.1:8000/sse--您应该看到一个流式响应。 - 检查你的
mcp.json用途"type": "http"以及确切的URLhttp://127.0.0.1:8000/sse. - 重新加载VS代码:
Ctrl+Shift+P→ 开发者:重新加载窗口. - 检查MCP日志:
Ctrl+Shift+P→ MCP:显示日志.
Q: 工具调用返回 422 Unprocessable Entity
所有布尔参数必须是JSON布尔值(true/false),不是字符串("true").所有整数参数必须是JSON数字,而不是字符串。
// Wrong
{"has_duplicates": "true", "has_long_functions": "false"}
// Correct
{"has_duplicates": true, "has_long_functions": false}
Q analyze_coverage 回报 "status": "error"
total_lines 被传递为 0。在调用此工具之前,请确保覆盖率工具已针对实际源文件运行。
测试
Q pytest 未找到
cd CodeBase
uv add pytest pytest-cov --dev
Q test_main_runs_mcp_server 失败与 OSError
端口8000已占用(活动服务器已在运行)。在运行测试之前停止它,因为此测试会模拟 FastMCP.run 但早期的测试运行可能使事件循环处于不良状态。终止服务器进程并重新运行。
Q: 添加新工具后覆盖率降至100%以下
为每个引入的新分支编写至少一个测试。运行:
cd CodeBase
uv run pytest test_main.py --cov=main --cov-report=term-missing
这 Missing 列将显示尚未覆盖的确切行。
安全与生产
Q: 在公共IP上公开此服务器安全吗?
否。服务器没有身份验证、TLS和速率限制。它仅用于本地/环回使用。对于任何网络部署,将其放置在具有HTTPS和API密钥验证的反向代理(例如nginx)之后。
Q: 如何向MCP服务器添加身份验证?
fastmcp 不提供内置的身份验证中间件。选项:
- 反向代理 --将nginx或Caddy放在前面,并需要一个承载令牌头。
- 定制中间件 --包装ASGI应用程序
mcp与StarletteBaseHTTPMiddleware这验证了一个秘密。 - 基于环境的秘密 --检查
os.environ["API_KEY"]在每个工具内并提高ValueError关于不匹配。
最后更新时间: 2026年3月12日
版本: 0.1.0