sosacrazy126
MCP 服务配置
复制以下 JSON 到 OPClaw 或其他 MCP 客户端的配置文件中即可使用
{
"mcpServers": {
"greptile": {
"args": [
"run",
"--rm",
"-i",
"-e",
"TRANSPORT=stdio",
"-e",
"GREPTILE_API_KEY",
"-e",
"GITHUB_TOKEN",
"-e",
"GREPTILE_BASE_URL",
"greptile-mcp"
],
"command": "docker",
"env": {
"GITHUB_TOKEN": "YOUR-GITHUB-TOKEN",
"GREPTILE_API_KEY": "YOUR-GREPTILE-API-KEY",
"GREPTILE_BASE_URL": "https://api.greptile.com/v2"
},
"transport": "stdio"
}
}
}
服务介绍
Greptile MCP 服务器 [已完成]
快速运行命令备忘单
✅ 项目状态:所有任务已完成 (11/11)
请参阅 PROJECT_COMPLETION.md 获取已完成工作的摘要,以及 USER_GUIDE.md 获取使用说明。
| 环境 | 设置与安装 | 运行命令 |
|---|---|---|
| 本地 (Python) | python -m venv .venv && source .venv/bin/activate && pip install -e . |
python -m src.main |
| Docker | docker build -t greptile-mcp . |
docker run --rm --env-file .env -p 8050:8050 greptile-mcp |
| Smithery | npm install -g smithery |
smithery deploy (见 smithery.yaml) |
在运行之前,请使用
.env.example填充.env并设置您的GREPTILE_API_KEY和GITHUB_TOKEN。
有关完整的先决条件、高级代理用法、集成和故障排除:
请参阅 docs/README.md 中的完整文档 和 AGENT_USAGE.md 中的代理详细信息。
这是一个实现了MCP(Model Context Protocol)协议的服务器,它与Greptile API集成,为AI代理提供代码搜索和查询功能。
功能
该服务器提供了四个基本的Greptile工具,使AI代理能够与代码库进行交互:
-
index_repository: 对代码库进行索引以支持代码搜索和查询。- 处理代码库使其可搜索
- 当代码库发生变化时更新现有索引
- 配置通知偏好
-
query_repository: 查询代码库以获取带有代码引用的答案。- 用自然语言询问关于代码库的问题
- 获取引用特定代码位置的详细答案
- 支持会话ID的历史对话
-
search_repository: 搜索代码库中相关的文件而不生成完整答案。- 查找与特定概念或特性相关的文件
- 获取按相关性排序的上下文匹配
- 当只需要文件位置时比完整查询更快
-
get_repository_info: 获取已索引代码库的信息。- 检查索引状态和进度
- 验证哪些代码库可用于查询
- 获取已索引代码库的元数据
Smithery 部署
Greptile MCP 服务器支持通过 Smithery 进行部署。项目根目录中包含一个 smithery.yaml 配置文件。
Smithery 配置
Smithery 配置在 smithery.yaml 中定义,并支持以下选项:
yaml
build:
dockerfile: Dockerfile
startCommand:
type: stdio
configSchema:
type: object
required:
- greptileApiKey
- githubToken
properties:
greptileApiKey:
type: string
description: "访问 Greptile API 的 API 密钥"
githubToken:
type: string
description: "用于仓库访问的 GitHub 个人访问令牌"
baseUrl:
type: string
description: "Greptile API 的基础 URL"
default: "https://api.greptile.com/v2"
host:
type: string
description: "使用 SSE 传输时绑定的主机"
default: "0.0.0.0"
port:
type: string
description: "使用 SSE 传输时监听的端口"
default: "8050"
使用 Smithery
要使用 Smithery 进行部署:
- 安装 Smithery:
npm install -g smithery - 部署服务器:
smithery deploy - 使用所需的 API 密钥配置您的 Smithery 客户端
其他文档有关AI代理的详细使用说明,请参阅代理使用指南。
先决条件
- Python 3.12+
- Greptile API密钥(来自https://app.greptile.com/settings/api)
- 对您打算索引的仓库具有
repo(或等效读取)权限的GitHub或GitLab个人访问令牌(PAT) - Docker(推荐用于部署)
必需的Python包
fastmcp- MCP服务器实现httpx- 异步HTTP客户端python-dotenv- 环境变量管理uvicorn- 用于SSE传输的ASGI服务器
安装
使用pip(适用于开发或本地测试)
-
克隆此仓库:
bash
git clone https://github.com/sosacrazy126/greptile-mcp.git
cd greptile-mcp -
创建虚拟环境(推荐):
bash
python -m venv .venv
source .venv/bin/activate # 在Windows上使用.venvScriptsactivate -
安装依赖项:
bash
pip install -e . -
根据
.env.example创建一个.env文件:
bash
cp .env.example .env -
在
.env文件中配置您的环境变量:GREPTILE_API_KEY=your_api_key_here
GITHUB_TOKEN=your_github_token_here
使用Docker(推荐用于部署)
-
克隆仓库:
bash
git clone https://github.com/sosacrazy126/greptile-mcp.git
cd greptile-mcp -
根据
.env.example创建一个.env文件并配置您的环境变量。 -
构建Docker镜像:
bash
docker build -t greptile-mcp .
运行服务器
使用pip
SSE传输(默认)
确保在您的.env文件中设置TRANSPORT=sse和PORT=8050(或您选择的端口)。
bash
python -m src.main
服务器将在http://<HOST>:<PORT>/sse监听。
Stdio传输
在您的.env文件中设置TRANSPORT=stdio。使用stdio时,MCP客户端通常会启动MCP服务器进程。
bash
通常由MCP客户端调用,而不是直接调用
TRANSPORT=stdio python -m src.main
使用Docker
SSE传输(默认)
bash
挂载.env文件进行配置,并映射端口
docker run --rm --env-file .env -p 8050:8050 greptile-mcp
服务器将在http://localhost:8050/sse(如果不是localhost,则为主机IP)监听。
Stdio传输
配置您的MCP客户端以运行带有TRANSPORT=stdio的Docker容器。
bash
使用stdio传输运行示例
docker run --rm -i --env-file .env -e TRANSPORT=stdio greptile-mcp
与MCP客户端集成
SSE配置示例
将以下内容添加到您的MCP客户端配置中(例如mcp_config.json):
json
{
"mcpServers": {
"greptile": {
"transport": "sse",
"url": "http://localhost:8050/sse"
}
}
}
Python与Stdio配置示例
确保在运行命令的环境中设置了TRANSPORT=stdio:
json
{
"mcpServers": {
"greptile": {
"transport": "stdio",
"command": "/path/to/your/greptile-mcp/.venv/bin/python",
"args": ["-m", "src.main"],
"env": {
"TRANSPORT": "stdio",
"GREPTILE_API_KEY": "YOUR-GREPTILE-API-KEY",
"GITHUB_TOKEN": "YOUR-GITHUB-TOKEN",
"GREPTILE_BASE_URL": "https://api.greptile.com/v2"
}
}
}
}
Docker与Stdio配置示例
json
{
"mcpServers": {
"greptile": {
"transport": "stdio",
"command": "docker",
"args": [
"run", "--rm", "-i",
"-e", "TRANSPORT=stdio",
"-e", "GREPTILE_API_KEY",
"-e", "GITHUB_TOKEN",
"-e", "GREPTILE_BASE_URL",
"greptile-mcp"
],
"env": {
"GREPTILE_API_KEY": "YOUR-GREPTILE-API-KEY",
"GITHUB_TOKEN": "YOUR-GITHUB-TOKEN",
"GREPTILE_BASE_URL": "https://api.greptile.com/v2"
}
}
}
}
详细使用指南### 代码库分析工作流程
- 使用
index_repository对您想要分析的仓库进行索引 - 使用
get_repository_info验证索引状态,以确保处理已完成 - 使用自然语言通过
query_repository查询仓库 - 使用
search_repository查找与特性或概念相关的特定文件
会话管理以保持对话上下文
当通过任何客户端(包括Smithery)与Greptile MCP服务器交互时,正确的会话管理对于维护对话上下文至关重要:
- 在对话开始时生成一个唯一的会话ID
- 对所有相关的后续查询重用相同的会话ID
- 开始新的对话时创建一个新的会话ID
示例会话ID管理:
python
生成一个唯一的会话ID
import uuid
session_id = str(uuid.uuid4())
初始查询
initial_response = query_repository(
query="身份验证是如何实现的?",
repositories=[{"remote": "github", "repository": "owner/repo", "branch": "main"}],
session_id=session_id # 包含会话ID
)
使用相同的会话ID进行后续查询
followup_response = query_repository(
query="你能提供更多关于JWT验证的细节吗?",
repositories=[{"remote": "github", "repository": "owner/repo", "branch": "main"}],
session_id=session_id # 重用相同的会话ID
)
对于Smithery集成的重要提示:通过Smithery连接的代理必须自己生成并维护会话ID。Greptile MCP服务器不会自动生成会话ID。会话ID应该是代理对话状态的一部分。
最佳实践
- 索引性能:较小的仓库索引速度更快。对于大型单体仓库,考虑仅索引特定分支或标签。
- 查询优化:在您的查询中具体明确。包含相关技术术语以获得更好的结果。
- 仓库选择:当查询多个仓库时,按相关性顺序列出它们以获得最佳结果。
- 会话管理:使用会话ID进行后续问题查询,以跨查询保持上下文。
API参考
1. 索引仓库
对仓库进行索引,以便在未来查询中可搜索。
参数:
remote(字符串):仓库主机,可以是"github"或"gitlab"repository(字符串):仓库格式为owner/repo(例如:"greptileai/greptile")branch(字符串):要索引的分支(例如:"main")reload(布尔值, 可选):是否强制重新处理已索引过的仓库notify(布尔值, 可选):索引完成后是否发送电子邮件通知
示例:
javascript
// 工具调用: index_repository
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main",
"reload": false,
"notify": false
}
响应:
json
{
"message": "已提交索引任务: greptileai/greptile",
"statusEndpoint": "https://api.greptile.com/v2/repositories/github:main:greptileai%2Fgreptile"
}
2. 查询仓库
使用自然语言查询仓库以获取带有代码引用的答案。
参数:
-
query(字符串):关于代码库的自然语言查询 -
repositories(数组):要查询的仓库列表,每个仓库格式如下:
json
{
"remote": "github",
"repository": "owner/repo",
"branch": "main"
} -
session_id(字符串, 可选):用于继续对话的会话ID -
stream(布尔值, 可选):是否流式传输响应 -
genius(布尔值, 可选):是否使用增强的查询功能
示例:
javascript
// 工具调用: query_repository
{
"query": "这个代码库中的身份验证是如何处理的?",
"repositories": [
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main"
}
],
"session_id": null,
"stream": false,
"genius": true
}
响应:
json
{
"message": "此代码库中的身份验证使用JWT令牌处理...",
"sources": [
{
"repository": "greptileai/greptile",
"remote": "github",
"branch": "main",
"filepath": "/src/auth/jwt.js",
"linestart": 14,
"lineend": 35,
"summary": "JWT令牌验证中间件"
}
]
}### 3. 搜索仓库
搜索仓库以查找相关文件,但不生成完整答案。
参数:
query(字符串):关于代码库的搜索查询repositories(数组):要搜索的仓库列表session_id(字符串, 可选):用于继续对话的会话IDgenius(布尔值, 可选):是否使用增强的搜索功能
示例:
javascript
// 工具调用: search_repository
{
"query": "Find files related to authentication middleware",
"repositories": [
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main"
}
],
"session_id": null,
"genius": true
}
响应:
json
{
"sources": [
{
"repository": "greptileai/greptile",
"remote": "github",
"branch": "main",
"filepath": "/src/auth/middleware.js",
"linestart": 1,
"lineend": 45,
"summary": "Authentication middleware implementation"
},
{
"repository": "greptileai/greptile",
"remote": "github",
"branch": "main",
"filepath": "/src/auth/jwt.js",
"linestart": 1,
"lineend": 78,
"summary": "JWT token handling functions"
}
]
}
4. 获取仓库信息
获取已索引的特定仓库的信息。
参数:
remote(字符串):仓库主机,可以是 "github" 或 "gitlab"repository(字符串):仓库格式为 owner/repobranch(字符串):被索引的分支
示例:
javascript
// 工具调用: get_repository_info
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main"
}
响应:
json
{
"repository": "greptileai/greptile",
"remote": "github",
"branch": "main",
"private": false,
"status": "COMPLETED",
"filesProcessed": 234,
"numFiles": 234,
"sha": "a1b2c3d4e5f6..."
}
集成示例
1. 通过Anthropic API与Claude.ai集成
python
from anthropic import Anthropic
import json
import requests
设置Anthropic客户端
anthropic = Anthropic(api_key="your_anthropic_key")
调用Greptile MCP的函数
def query_code(question, repositories):
response = requests.post(
"http://localhost:8050/tools/greptile/query_repository",
json={
"query": question,
"repositories": repositories,
"genius": True
}
)
return json.loads(response.text)
使用增强的代码上下文询问Claude
def ask_claude_with_code_context(question, repositories):
# 从Greptile获取代码上下文
code_context = query_code(question, repositories)
# 为Claude格式化上下文
formatted_context = f"Code Analysis Result:\n{code_context['message']}\n\nRelevant Files:\n"
for source in code_context.get('sources', []):
formatted_context += f"- {source['filepath']} (lines {source['linestart']}-{source['lineend']})\n"
# 将带有上下文的消息发送给Claude
message = anthropic.messages.create(
model="claude-3-opus-20240229",
max_tokens=1000,
messages=[
{"role": "user", "content": f"Based on this code context:\n\n{formatted_context}\n\nQuestion: {question}"}
]
)
return message.content
示例用法
answer = ask_claude_with_code_context(
"How does the authentication system work?",
[{"remote": "github", "repository": "greptileai/greptile", "branch": "main"}]
)
print(answer)
2. 与基于LLM的聊天机器人集成
python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import httpx
import json
app = FastAPI()
Greptile MCP端点
GREPTILE_MCP_URL = "http://localhost:8050/tools/greptile"
@app.post("/chat")
async def chat_endpoint(request: Request):
data = await request.json()
user_message = data.get("message", "")
# 检查这是否是一个与代码相关的提问
if "code" in user_message or "repository" in user_message or "function" in user_message:
# 通过Greptile MCP查询仓库
async with httpx.AsyncClient() as client:
response = await client.post(
f"{GREPTILE_MCP_URL}/query_repository",
json={
"query": user_message,
"repositories": [
{"remote": "github", "repository": "your-org/your-repo", "branch": "main"}
],
"genius": True
}
)
greptile_result = response.json()
# 处理结果并返回给用户
answer = greptile_result.get("message", "")
sources = greptile_result.get("sources", [])
return JSONResponse({
"message": answer,
"code_references": sources
})
# 对于非代码问题,使用您的常规LLM
return JSONResponse({
"message": "This appears to be a general question. I'll handle it normally."
})
运行命令: uvicorn app:app --reload### 3. 命令行代码查询工具
python
#!/usr/bin/env python3
import argparse
import json
import requests
import sys
def main():
parser = argparse.ArgumentParser(description="使用自然语言查询代码仓库")
parser.add_argument("query", help="关于代码的自然语言查询")
parser.add_argument("--repo", "-r", required=True, help="仓库格式为 github:owner/repo:branch")
parser.add_argument("--genius", "-g", action="store_true", help="使用增强的查询功能")
args = parser.parse_args()
# 解析仓库字符串
try:
remote, repo_path = args.repo.split(":", 1)
if ":" in repo_path:
repo, branch = repo_path.split(":", 1)
else:
repo = repo_path
branch = "main"
except ValueError:
print("错误:仓库必须是格式为 github:owner/repo:branch 或者 github:owner/repo")
sys.exit(1)
# 准备请求
payload = {
"query": args.query,
"repositories": [
{
"remote": remote,
"repository": repo,
"branch": branch
}
],
"genius": args.genius
}
# 发送请求
try:
response = requests.post(
"http://localhost:8050/tools/greptile/query_repository",
json=payload
)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"错误:{e}")
sys.exit(1)
# 处理响应
result = response.json()
# 显示答案
print("
=== 答案 ===
")
print(result.get("message", "未找到答案"))
# 显示来源
sources = result.get("sources", [])
if sources:
print("
=== 代码引用 ===
")
for i, source in enumerate(sources, 1):
print(f"{i}. {source['filepath']} (行 {source.get('linestart', '?')}-{source.get('lineend', '?')})")
print(f" 仓库: {source['repository']} ({source['branch']})")
if 'summary' in source:
print(f" 摘要: {source['summary']}")
print()
if name == "main":
main()
故障排除
常见问题
1. 认证失败
症状:您收到 401 Unauthorized 或 Repository not found with configured credentials 错误。
解决方案:
- 验证您的 Greptile API 密钥是否有效,并且在
.env文件中正确设置 - 检查您的 GitHub/GitLab 令牌是否已过期(它们通常会在一段时间后过期)
- 确保您的 GitHub/GitLab 令牌具有访问仓库所需的
repo范围 - 直接通过 GitHub API 测试您的 GitHub 令牌以验证其是否正常工作
测试 GitHub 令牌:
bash
curl -H "Authorization: token YOUR_GITHUB_TOKEN" https://api.github.com/user
2. 仓库未找到
症状:API 返回 404 错误或“仓库未找到”消息。
解决方案:
- 验证仓库是否存在并且可以使用您的 GitHub/GitLab 令牌访问
- 双重检查仓库格式(应为
owner/repo) - 对于私有仓库,确保您的令牌具有适当的访问权限
- 验证分支名称是否正确
3. 连接问题
症状:无法连接到 MCP 服务器。
解决方案:
- 检查服务器是否正在运行 (
ps aux | grep src.main) - 验证端口未被其他应用程序占用
- 检查网络设置和防火墙配置
- 尝试通过更改
.env文件中的PORT值来使用不同的端口
4. Docker 问题
症状:Docker 容器无法启动或正常运行。
解决方案:
- 检查 Docker 日志:
docker logs <container_id> - 验证
.env文件是否正确挂载 - 确保
docker run命令中的端口映射正确 - 检查 Docker 网络配置是否允许所需连接
日志和调试要启用更详细的日志记录,请设置以下环境变量:
bash
添加到你的 .env 文件中
DEBUG=true
LOG_LEVEL=debug
对于特定的MCP交互故障排除,请检查MCP服务器日志:
bash
以增强的日志记录运行
LOG_LEVEL=debug python -m src.main
高级配置
环境变量
| 变量 | 描述 | 默认值 |
|---|---|---|
TRANSPORT |
传输方法 (sse 或 stdio) |
sse |
HOST |
SSE传输绑定的主机 | 0.0.0.0 |
PORT |
SSE传输端口 | 8050 |
GREPTILE_API_KEY |
您的Greptile API密钥 | (必需) |
GITHUB_TOKEN |
GitHub/GitLab个人访问令牌 | (必需) |
GREPTILE_BASE_URL |
Greptile API基础URL | https://api.greptile.com/v2 |
DEBUG |
启用调试模式 | false |
LOG_LEVEL |
日志级别 | info |
自定义API端点
如果您需要使用自定义的Greptile API端点(例如,用于企业安装),请修改GREPTILE_BASE_URL环境变量:
GREPTILE_BASE_URL=https://greptile.your-company.com/api/v2
性能调优
对于生产部署,请考虑这些性能优化措施:
-
工作进程配置:当使用Uvicorn进行SSE传输时,配置适当的工作进程数量:
bash对于CPU密集型应用:workers = 1-2 × CPU核心数
uvicorn src.main:app --workers 4
-
超时设置:为大型仓库调整超时时间:
添加到 .env 中
GREPTILE_TIMEOUT=120.0 # 默认是60.0秒
-
内存优化:对于大规模部署,考虑容器资源限制:
bash
docker run --rm --env-file .env -p 8050:8050 --memory="1g" --cpus="1.0" greptile-mcp
贡献
欢迎贡献!请随时提交Pull Request。
- 分叉仓库
- 创建您的功能分支 (
git checkout -b feature/amazing-feature) - 提交更改 (
git commit -m 'Add some amazing feature') - 推送到分支 (
git push origin feature/amazing-feature) - 打开一个Pull Request
开发环境设置
开发时,安装额外依赖项:
bash
pip install -e ".[dev]"
运行测试:
bash
pytest
许可证
本项目根据MIT许可证发布 - 详情请参阅 LICENSE 文件。