Greptile MCP 服务器 [已完成]
快速运行命令备忘单
✅ 项目状态:所有任务已完成(11/11)
请参阅PROJECT_COMPLETION.md了解已完成工作的摘要,并参阅USER_GUIDE.md了解使用说明。
环境 | 设置和安装 | 运行命令 |
本地(Python) |
|
|
Docker |
|
|
锻造工艺 |
|
|
使用
.env.example填写.env并在运行之前设置您的GREPTILE_API_KEY和GITHUB_TOKEN。
有关完整的先决条件、高级代理使用、集成和故障排除:请参阅
MCP(模型上下文协议)服务器实现与 Greptile API 集成,为 AI 代理提供代码搜索和查询功能。
特征
该服务器提供了四个基本的 Greptile 工具,使 AI 代理能够与代码库进行交互:
index_repository:索引存储库以进行代码搜索和查询。处理存储库以使其可搜索
当存储库更改时更新现有索引
配置通知首选项
query_repository:查询存储库以获取带有代码参考的答案。询问有关代码库的自然语言问题
获取引用特定代码位置的详细答案
支持使用会话 ID 的对话历史记录
search_repository:在存储库中搜索相关文件,但不生成完整答案。查找与特定概念或功能相关的文件
获取按相关性排序的上下文匹配
当仅需要文件位置时,比完整查询更快
get_repository_info:获取有关索引存储库的信息。检查索引状态和进度
验证哪些存储库可供查询
获取有关索引存储库的元数据
Related MCP server: Graphiti MCP Server
Smithery部署
Greptile MCP 服务器支持通过 Smithery 进行部署。项目根目录中包含一个smithery.yaml配置文件。
Smithery 配置
Smithery 配置在smithery.yaml中定义,并支持以下选项:
build:
dockerfile: Dockerfile
startCommand:
type: stdio
configSchema:
type: object
required:
- greptileApiKey
- githubToken
properties:
greptileApiKey:
type: string
description: "API key for accessing the Greptile API"
githubToken:
type: string
description: "GitHub Personal Access Token for repository access"
baseUrl:
type: string
description: "Base URL for Greptile API"
default: "https://api.greptile.com/v2"
host:
type: string
description: "Host to bind to when using SSE transport"
default: "0.0.0.0"
port:
type: string
description: "Port to listen on when using SSE transport"
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 )
**GitHub 或 GitLab 个人访问令牌 (PAT),**具有您要索引的存储库的
repo(或等效读取) 权限Docker (推荐部署)
所需的 Python 包
fastmcp——MCP 服务器实现httpx- 异步 HTTP 客户端python-dotenv- 环境变量管理uvicorn- 用于 SSE 传输的 ASGI 服务器
安装
使用 pip(用于开发或本地测试)
克隆此存储库:
git clone https://github.com/sosacrazy126/greptile-mcp.git cd greptile-mcp创建虚拟环境(推荐):
python -m venv .venv source .venv/bin/activate # On Windows use `.venv\Scripts\activate`安装依赖项:
pip install -e .根据
.env.example创建.env文件:cp .env.example .env在
.env文件中配置环境变量:GREPTILE_API_KEY=your_api_key_here GITHUB_TOKEN=your_github_token_here
使用 Docker(推荐部署)
克隆存储库:
git clone https://github.com/sosacrazy126/greptile-mcp.git cd greptile-mcp根据
.env.example创建一个.env文件并配置您的环境变量。构建 Docker 镜像:
docker build -t greptile-mcp .
运行服务器
使用 pip
SSE 传输(默认)
确保在.env文件中设置了TRANSPORT=sse和PORT=8050 (或您选择的端口)。
python -m src.main服务器将监听http://<HOST>:<PORT>/sse 。
标准传输
在.env文件中设置TRANSPORT=stdio 。使用 stdio 时,MCP 客户端通常会启动 MCP 服务器进程。
# Usually invoked by an MCP client, not directly
TRANSPORT=stdio python -m src.main使用 Docker
SSE 传输(默认)
# Mounts the .env file for configuration and maps the port
docker run --rm --env-file .env -p 8050:8050 greptile-mcp服务器将监听http://localhost:8050/sse (如果不是 localhost,则为主机 IP)。
标准传输
配置您的 MCP 客户端以使用TRANSPORT=stdio运行 Docker 容器。
# Example of running with stdio transport
docker run --rm -i --env-file .env -e TRANSPORT=stdio greptile-mcp与 MCP 客户端集成
SSE配置示例
将其添加到您的 MCP 客户端的配置中(例如mcp_config.json ):
{
"mcpServers": {
"greptile": {
"transport": "sse",
"url": "http://localhost:8050/sse"
}
}
}Python 与 Stdio 配置示例
确保在运行命令的环境中设置了TRANSPORT=stdio :
{
"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 配置示例
{
"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 管理示例:
# Generate a unique session ID
import uuid
session_id = str(uuid.uuid4())
# Initial query
initial_response = query_repository(
query="How is authentication implemented?",
repositories=[{"remote": "github", "repository": "owner/repo", "branch": "main"}],
session_id=session_id # Include the session ID
)
# Follow-up query using the SAME session ID
followup_response = query_repository(
query="Can you provide more details about the JWT verification?",
repositories=[{"remote": "github", "repository": "owner/repo", "branch": "main"}],
session_id=session_id # Reuse the same session ID
)Smithery 集成重要提示:通过 Smithery 连接的代理必须生成并维护自己的会话 ID。Greptile MCP 服务器不会自动生成会话 ID。会话 ID 应包含在代理的对话状态中。
最佳实践
索引性能:较小的存储库索引速度更快。对于大型的单一存储库,请考虑索引特定的分支或标签。
查询优化:查询时务必具体。包含相关的技术术语,以获得更好的结果。
存储库选择:查询多个存储库时,按相关性顺序列出它们以获得最佳结果。
会话管理:使用会话 ID 来跟踪后续问题,以维护查询的上下文。
API 参考
1. 索引库
对存储库进行索引,以便在将来的查询中可以搜索它。
参数:
remote(字符串):存储库主机,可以是“github”或“gitlab”repository(字符串):所有者/repo 格式的存储库(例如“greptileai/greptile”)branch(字符串):要索引的分支(例如“main”)reload(布尔值,可选):是否强制重新处理先前索引的存储库notify(布尔值,可选):索引完成时是否发送电子邮件通知
例子:
// Tool Call: index_repository
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main",
"reload": false,
"notify": false
}回复:
{
"message": "Indexing Job Submitted for: greptileai/greptile",
"statusEndpoint": "https://api.greptile.com/v2/repositories/github:main:greptileai%2Fgreptile"
}2. 查询存储库
使用自然语言查询存储库以获取带有代码参考的答案。
参数:
query(字符串):关于代码库的自然语言查询repositories(数组):要查询的存储库列表,每个存储库的格式如下:{ "remote": "github", "repository": "owner/repo", "branch": "main" }session_id(字符串,可选):用于继续对话的会话 IDstream(布尔值,可选):是否流式传输响应genius(布尔值,可选):是否使用增强查询功能
例子:
// Tool Call: query_repository
{
"query": "How is authentication handled in this codebase?",
"repositories": [
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main"
}
],
"session_id": null,
"stream": false,
"genius": true
}回复:
{
"message": "Authentication in this codebase is handled using JWT tokens...",
"sources": [
{
"repository": "greptileai/greptile",
"remote": "github",
"branch": "main",
"filepath": "/src/auth/jwt.js",
"linestart": 14,
"lineend": 35,
"summary": "JWT token validation middleware"
}
]
}3. 搜索存储库
搜索存储库以查找相关文件但不生成完整答案。
参数:
query(字符串):关于代码库的搜索查询repositories(数组):要搜索的存储库列表session_id(字符串,可选):用于继续对话的会话 IDgenius(布尔值,可选):是否使用增强搜索功能
例子:
// Tool Call: search_repository
{
"query": "Find files related to authentication middleware",
"repositories": [
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main"
}
],
"session_id": null,
"genius": true
}回复:
{
"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(字符串):所有者/repo 格式的存储库branch(字符串):被索引的分支
例子:
// Tool Call: get_repository_info
{
"remote": "github",
"repository": "greptileai/greptile",
"branch": "main"
}回复:
{
"repository": "greptileai/greptile",
"remote": "github",
"branch": "main",
"private": false,
"status": "COMPLETED",
"filesProcessed": 234,
"numFiles": 234,
"sha": "a1b2c3d4e5f6..."
}集成示例
1. 通过 Anthropic API 与 Claude.ai 集成
from anthropic import Anthropic
import json
import requests
# Set up Anthropic client
anthropic = Anthropic(api_key="your_anthropic_key")
# Function to call 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)
# Ask Claude with enhanced code context
def ask_claude_with_code_context(question, repositories):
# Get code context from Greptile
code_context = query_code(question, repositories)
# Format the context for 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"
# Send to Claude with context
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
# Example usage
answer = ask_claude_with_code_context(
"How does the authentication system work?",
[{"remote": "github", "repository": "greptileai/greptile", "branch": "main"}]
)
print(answer)2. 与基于 LLM 的聊天机器人集成
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import httpx
import json
app = FastAPI()
# Greptile MCP endpoint
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", "")
# Check if this is a code-related question
if "code" in user_message or "repository" in user_message or "function" in user_message:
# Query the repository through 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()
# Process the result and return to the user
answer = greptile_result.get("message", "")
sources = greptile_result.get("sources", [])
return JSONResponse({
"message": answer,
"code_references": sources
})
# For non-code questions, use your regular LLM
return JSONResponse({
"message": "This appears to be a general question. I'll handle it normally."
})
# Run with: uvicorn app:app --reload3. 命令行代码查询工具
#!/usr/bin/env python3
import argparse
import json
import requests
import sys
def main():
parser = argparse.ArgumentParser(description="Query code repositories using natural language")
parser.add_argument("query", help="The natural language query about the code")
parser.add_argument("--repo", "-r", required=True, help="Repository in format github:owner/repo:branch")
parser.add_argument("--genius", "-g", action="store_true", help="Use enhanced query capabilities")
args = parser.parse_args()
# Parse the repository string
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("Error: Repository must be in format 'github:owner/repo:branch' or 'github:owner/repo'")
sys.exit(1)
# Prepare the request
payload = {
"query": args.query,
"repositories": [
{
"remote": remote,
"repository": repo,
"branch": branch
}
],
"genius": args.genius
}
# Make the request
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"Error: {e}")
sys.exit(1)
# Process the response
result = response.json()
# Display the answer
print("\n=== ANSWER ===\n")
print(result.get("message", "No answer found"))
# Display the sources
sources = result.get("sources", [])
if sources:
print("\n=== CODE REFERENCES ===\n")
for i, source in enumerate(sources, 1):
print(f"{i}. {source['filepath']} (lines {source.get('linestart', '?')}-{source.get('lineend', '?')})")
print(f" Repository: {source['repository']} ({source['branch']})")
if 'summary' in source:
print(f" Summary: {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 令牌:
curl -H "Authorization: token YOUR_GITHUB_TOKEN" https://api.github.com/user2. 未找到存储库
症状: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 网络配置是否允许所需的连接
日志和调试
要启用更详细的日志记录,请设置以下环境变量:
# Add to your .env file
DEBUG=true
LOG_LEVEL=debug要对特定的 MCP 交互进行故障排除,请检查 MCP 服务器日志:
# Run with enhanced logging
LOG_LEVEL=debug python -m src.main高级配置
环境变量
多变的 | 描述 | 默认 |
| 传输方法( |
|
| 绑定到 SSE 传输的主机 |
|
| SSE运输港口 |
|
| 您的 Greptile API 密钥 | (必需的) |
| GitHub/GitLab 个人访问令牌 | (必需的) |
| Greptile API 基本 URL |
|
| 启用调试模式 |
|
| 日志级别 |
|
自定义 API 端点
如果您需要使用自定义 Greptile API 端点(例如,用于企业安装),请修改GREPTILE_BASE_URL环境变量:
GREPTILE_BASE_URL=https://greptile.your-company.com/api/v2性能调优
对于生产部署,请考虑以下性能优化:
工作者配置:当使用 Uvicorn 的 SSE 传输时,配置适当的工作者数量:
# For CPU-bound applications: workers = 1-2 × CPU cores uvicorn src.main:app --workers 4超时设置:调整大型存储库的超时:
# Add to .env GREPTILE_TIMEOUT=120.0 # Default is 60.0 seconds内存优化:对于大型部署,请考虑容器资源限制:
docker run --rm --env-file .env -p 8050:8050 --memory="1g" --cpus="1.0" greptile-mcp
贡献
欢迎贡献代码!欢迎提交 Pull 请求。
分叉存储库
创建你的功能分支(
git checkout -b feature/amazing-feature)提交您的更改(
git commit -m 'Add some amazing feature')推送到分支(
git push origin feature/amazing-feature)打开拉取请求
开发设置
为了开发,请安装其他依赖项:
pip install -e ".[dev]"运行测试:
pytest执照
该项目根据 MIT 许可证获得许可 - 有关详细信息,请参阅 LICENSE 文件。