🤖 Bitbucket MCP服务器教程
   
🚀 构建与您的Bitbucket工作流程集成的人工智能代码审查机器人!
一个全面的教程,用于构建一个 模型上下文协议(MCP)服务器 它将Claude Desktop和Cursor等人工智能助手连接到Bitbucket存储库,以进行智能代码审查和存储库管理。
⭐ 为什么是这个教程?
- 🎯 生产准备就绪:配备11个工具和4个资源的完整服务器
- 📚 初学者友好:带有复制粘贴代码片段的分步指南
- 🤖 人工智能集成:适用于Claude Desktop、Cursor和任何兼容MCP的AI
- 🔧 实际使用情况:实际的PR审查自动化,而不仅仅是API演示
- ⚡ 快速设置:在10分钟内跑步
🎯 你将学到什么
- MCP基础:了解模型上下文协议及其如何将AI助手连接到外部工具
- 服务器开发:使用FastMCP框架构建生产就绪的MCP服务器
- API集成:连接到Bitbucket的REST API以进行存储库操作
- AI助手集成:配置Claude Desktop和Cursor以使用您的MCP服务器
🚀 此服务器的功能
将您的AI助手转化为 强大的开发伙伴 这可以:
🔧 库管理
- 📋 通过智能过滤列出并探索Bitbucket存储库
- 📊 获取详细的存储库分析和元数据
- 🔍 通过MCP资源访问存储库数据以进行复杂查询
🔀 拉取请求自动化
- 📝 自动列出、审查和分析拉取请求
- 💻 获取详细的PR信息并完成代码差异
- ⚡ 使用人工智能推理管理公关工作流程(批准、合并、拒绝)
- 💬 添加智能评论并参与协作评论
🤖 AI驱动的代码审查
- 🔍 使用上下文感知建议分析代码更改
- 📈 识别潜在问题、优化和最佳实践
- 🎯 自动生成有意义的代码审查注释
- 🔄 在人工智能的帮助下简化整个审核过程
真实示例: *“嘿,克劳德,查看我的回购中的最新PR,并提出改进建议”* → 你的AI助手获取PR,分析差异,并提供详细的代码审查反馈!
📋 先决条件
- Python 3.8+ (推荐使用Python 3.9+)
- Bitbucket账户 具有API访问权限
- Python基础知识 (变量、函数、async/await)
- 代码编辑器 (VS代码、光标或类似对象)
🏗️ 项目结构(教程就绪)
bitbucket-mcp-tutorial/
├── README.md # This comprehensive guide
├── LICENSE # MIT license
├── mcp_server.py # Main MCP server (simplified & commented)
├── bitbucket_client.py # Bitbucket API client
├── test_mcp_server.py # Test script to verify functionality
├── config_helper.py # Helper for generating configurations
├── requirements.txt # Python dependencies
├── .env.example # Environment variables template
└── docs/
└── ARCHITECTURE.md # System design and data flow⚡ 快速入门(5分钟)
1.克隆和设置
git clone https://github.com/shibyan-ai-engineer/bitbucket-mcp-tutorial
cd bitbucket-mcp-tutorial
pip install -r requirements.txt2.配置环境
cp .env.example .env
# Edit .env with your Bitbucket credentials3.测试服务器
python test_mcp_server.py --quick4.配置AI助手
python config_helper.py🔧 详细设置指南
步骤1:Python环境设置
选项A:使用pip(建议初学者使用)
# Create project directory
mkdir bitbucket-mcp-tutorial
cd bitbucket-mcp-tutorial
# Install dependencies
pip install -r requirements.txt选项B:使用虚拟环境(建议用于生产)
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\\Scripts\\activate
# Install dependencies
pip install -r requirements.txt步骤2:Bitbucket API配置
- 创建应用程序密码:
- 转到Bitbucket→ 设置→ 个人设置→ 应用密码 - 使用以下命令创建新的应用程序密码:存储库(读取、写入)、拉取请求(读取、写) - 安全地保存生成的密码
- 配置环境变量:
cp .env.example .env编辑 .env 文件:
BITBUCKET_WORKSPACE=your-workspace-name
BITBUCKET_USERNAME=your-username
BITBUCKET_APP_PASSWORD=your-app-password步骤3:测试您的设置
快速测试 (30秒):
python test_mcp_server.py --quick全面测试 (2分钟):
python test_mcp_server.py预期产量:
✅ Successfully imported Bitbucket MCP server
✅ Connected successfully!
🔧 Available Tools (11): [list of all tools]
📂 Available Resources (4): [list of all resources]
✅ All tests completed successfully!步骤4:配置AI助手
适用于克劳德桌面:
python config_helper.py --claude对于光标:
python config_helper.py --cursor手动配置: 配置助手将向您准确显示要添加到AI助手配置文件中的内容。
🎓 理解代码
核心组件
1.MCP服务器(mcp_server.py)
- FastMCP框架设置
- 11个Bitbucket操作工具
- 4个数据访问资源
- 错误处理和日志
2.比特桶客户端(bitbucket_client.py)
- Bitbucket API的HTTP客户端
- 身份验证处理
- 请求/响应处理
3.测试脚本(test_mcp_server.py)
- 全面的功能测试
- 性能基准测试
- 集成验证
关键工具详解
# Tool 1: List Repositories
@mcp.tool
async def list_repositories(role: str = "member"):
"""List repositories by user role"""
# Implementation details...
# Tool 2: Get Repository Info
@mcp.tool
async def get_repository_info(repo_slug: str):
"""Get detailed repository information"""
# Implementation details...
# Tool 3: List Pull Requests
@mcp.tool
async def list_pull_requests(repo_slug: str, state: str = "OPEN"):
"""List pull requests with filtering"""
# Implementation details...资源详解
# Resource 1: Repositories List
@mcp.resource("bitbucket://repositories")
async def get_repositories_resource():
"""Provide access to repositories data"""
# Implementation details...
# Resource 2: Specific Repository
@mcp.resource("bitbucket://repo/{repo_slug}")
async def get_repository_resource(repo_slug: str):
"""Provide access to specific repository data"""
# Implementation details...🔗 与AI助手集成
Claude桌面集成
运行后 python config_helper.py --claude,将生成的配置添加到:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json 视窗: %APPDATA%\\Claude\\claude_desktop_config.json
配置示例:
{
"mcpServers": {
"bitbucket": {
"command": "python",
"args": ["/absolute/path/to/mcp_server.py"],
"env": {
"BITBUCKET_WORKSPACE": "your-workspace",
"BITBUCKET_USERNAME": "your-username",
"BITBUCKET_APP_PASSWORD": "your-app-password"
}
}
}
}光标集成
运行后 python config_helper.py --cursor,将生成的配置添加到游标设置中。
📊 结构概述
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ AI Assistant │ │ MCP Server │ │ Bitbucket │
│ │ │ │ │ │
│ Claude Desktop │◄──►│ 11 Tools │◄──►│ REST API │
│ Cursor │ │ 4 Resources │ │ Repositories │
│ │ │ FastMCP │ │ Pull Requests │
└─────────────────┘ └──────────────────┘ └─────────────────┘数据流
- 用户请求:“查看我存储库中的最新PR”
- AI助手:解析请求并调用MCP工具
- MCP服务器:使用Bitbucket API处理工具调用
- 比特桶API:返回存储库和PR数据
- MCP服务器:为AI助手格式化响应
- AI助手:向用户呈现智能分析
🛠️ 可用工具和资源
🔧 工具(共11个)
| 工具 | 用途 | 参数 |
|---|---|---|
list_repositories | 列出用户存储库 | role (管理员/成员/贡献者) |
get_repository_info | 获取回购详细信息 | repo_slug |
list_pull_requests | 列出PR | repo_slug, state |
get_pull_request_info | 获取PR详细信息 | repo_slug, pr_id |
get_pull_request_diff | 获取PR代码差异 | repo_slug, pr_id |
add_pr_comment | 添加PR评论 | repo_slug, pr_id, content |
approve_pr | 批准PR | repo_slug, pr_id |
unapprove_pr | 删除批准 | repo_slug, pr_id |
merge_pr | 合并PR | repo_slug, pr_id, merge_strategy |
decline_pr | 拒绝公关 | repo_slug, pr_id, reason |
get_pr_comments | 获取公关评论 | repo_slug, pr_id |
📂 资源(共4个)
| 资源 | URI模式 | 目的 |
|---|---|---|
| 存储库 | bitbucket://repositories | 列出所有存储库 |
| 存储库 | bitbucket://repo/{repo_slug} | 特定存储库数据 |
| 拉取请求 | bitbucket://repo/{repo_slug}/pullrequests | 存储库的PR |
| PR评论 | bitbucket://pr/{repo_slug}/{pr_id}/comments | 公关评论 |
🎪 现场演示使用示例
🔥 AI驱动的代码审查在行动
👤 You: "Review the latest PR in my-webapp-project"
🤖 AI Assistant:
✅ Found PR #42: "Add user authentication system"
📊 Analyzing 15 changed files, 342 additions, 89 deletions...
🔍 Code Review Summary:
• Strong implementation of JWT authentication
• Potential security issue: password validation needs strengthening
• Suggest adding rate limiting to login endpoint
• Missing unit tests for auth middleware
• Database migration looks good
💬 Posted detailed review comment with specific line suggestions!👤 You: "What repositories need urgent attention?"
🤖 AI Assistant:
📋 Analyzed 12 repositories across your workspace:
🚨 High Priority:
• "mobile-app" - 3 open PRs over 2 weeks old
• "api-service" - Security vulnerability in dependencies
⚠️ Medium Priority:
• "frontend-dashboard" - 1 large PR awaiting review
• "data-pipeline" - No recent activity, stale issues
✅ All Good:
• "docs-site", "config-service", "monitoring-tools"🎯 存储库探索
👤 You: "What repositories do I have access to in the mobile team workspace?"
🤖 AI Assistant: Found 8 repositories with 'mobile' relevance:
📱 "ios-app" (Swift) - 2.3MB, updated 2 days ago
🤖 "android-app" (Kotlin) - 5.1MB, updated yesterday
🔧 "mobile-api" (Python) - 1.8MB, updated 3 hours ago
...🐛 故障排除
常见问题
1.导入错误
# Error: ModuleNotFoundError: No module named 'fastmcp'
# Solution: Install dependencies
pip install -r requirements.txt2.身份验证错误
# Error: Unauthorized (401)
# Solution: Check .env file configuration
python config_helper.py --test-auth3.服务器连接问题
# Error: Connection refused
# Solution: Test server locally first
python test_mcp_server.py --quick调试模式
运行调试日志:
FASTMCP_DEBUG=1 python mcp_server.py运行具有详细输出的测试:
python test_mcp_server.py --verbose📚 学习资源
后续步骤
- 探索代码:通读
mcp_server.py带有教育性评论 - 尝试现场示例:使用配置的AI助手与存储库交互
- 扩展功能:为问题、分支或提交添加新工具
- 建立自己的:为其他API(GitHub、GitLab等)创建MCP服务器
其他文件
docs/ARCHITECTURE.md-详细的系统设计和技术概述
外部资源
🤝 贡献
本教程项目欢迎改进! 星⭐ 此回购 如果它能帮助你构建令人惊叹的人工智能开发工具!
🎯 贡献领域:
- 🔧 其他Bitbucket API集成(问题、部署、管道)
- 🛡️ 增强的错误处理和重试机制
- 🧪 更全面的测试覆盖率
- 📖 文件改进和翻译
- 💡 示例用例和AI提示策略
- 🔗 其他AI助手的集成指南
加入我们的AI开发者社区! 🚀
📄 许可证
麻省理工学院许可证-欢迎使用本教程学习、教学和构建出色的人工智能工具!
______________________________________________________________________
⭐ 喜欢这个项目吗?给它一颗星!
🎯 准备好彻底改变你的代码审查流程了吗?跑 python test_mcp_server.py --quick 开始吧!
内置于❤️ 面向人工智能驱动的开发社区
