Skip to main content
Glama

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 build -t greptile-mcp .

docker run --rm --env-file .env -p 8050:8050 greptile-mcp

鍛冶屋

npm install -g smithery

smithery deploy (smithery.yaml を参照)

実行する前に、 .env.exampleを使用して.envに入力し、 GREPTILE_API_KEYGITHUB_TOKENを設定します。

完全な前提条件、高度なエージェントの使用、統合、およびトラブルシューティングについては、 docs/README.md


Greptile API と統合して AI エージェントにコード検索およびクエリ機能を提供する MCP (モデル コンテキスト プロトコル) サーバー実装。

鍛冶屋のバッジ

特徴

サーバーは、AI エージェントがコードベースと対話できるようにする 4 つの重要な Greptile ツールを提供します。

  1. index_repository : コードの検索とクエリのためにリポジトリをインデックスします。

    • リポジトリを検索可能に処理する

    • リポジトリが変更されたときに既存のインデックスを更新する

    • 通知設定を構成する

  2. query_repository : リポジトリをクエリして、コード参照を含む回答を取得します。

    • コードベースについて自然言語で質問する

    • 特定のコードの場所を参照する詳細な回答を取得します

    • セッションIDによる会話履歴のサポート

  3. search_repository : 完全な回答を生成せずに、関連するファイルのリポジトリを検索します。

    • 特定の概念や機能に関連するファイルを検索する

    • 関連性に基づいてランク付けされたコンテキストマッチを取得します

    • ファイルの場所のみが必要な場合、完全なクエリよりも高速です

  4. get_repository_info : インデックス化されたリポジトリに関する情報を取得します。

    • インデックス作成のステータスと進行状況を確認する

    • クエリに使用できるリポジトリを確認する

    • インデックスされたリポジトリに関するメタデータを取得する

Related MCP server: Graphiti MCP Server

鍛冶屋の展開

Greptile MCPサーバーはSmithery経由のデプロイメントをサポートしています。smithery.yaml設定ファイルsmithery.yamlプロジェクトルートに含まれています。

鍛冶屋の構成

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 を使用してデプロイするには:

  1. Smitheryをインストールします: npm install -g smithery

  2. サーバーをデプロイする: smithery deploy

  3. 必要なAPIキーを使用してSmiseryクライアントを構成する

追加ドキュメント

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 の使用(開発またはローカルテスト用)

  1. このリポジトリをクローンします:

    git clone https://github.com/sosacrazy126/greptile-mcp.git
    cd greptile-mcp
  2. 仮想環境を作成します (推奨):

    python -m venv .venv
    source .venv/bin/activate  # On Windows use `.venv\Scripts\activate`
  3. 依存関係をインストールします:

    pip install -e .
  4. .env.exampleに基づいて.envファイルを作成します。

    cp .env.example .env
  5. .envファイルで環境変数を設定します。

    GREPTILE_API_KEY=your_api_key_here
    GITHUB_TOKEN=your_github_token_here

Docker の使用 (デプロイメントに推奨)

  1. リポジトリをクローンします。

    git clone https://github.com/sosacrazy126/greptile-mcp.git
    cd greptile-mcp
  2. .env.exampleに基づいて.envファイルを作成し、環境変数を構成します。

  3. Docker イメージをビルドします。

    docker build -t greptile-mcp .

サーバーの実行

pipの使用

SSEトランスポート(デフォルト)

.envファイルでTRANSPORT=sseおよびPORT=8050 (または選択したポート) が設定されていることを確認します。

python -m src.main

サーバーはhttp://<HOST>:<PORT>/sseをリッスンします。

Stdioトランスポート

.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) をリッスンします。

Stdioトランスポート

TRANSPORT=stdioを使用して Docker コンテナを実行するように MCP クライアントを構成します。

# 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"
      }
    }
  }
}

詳細な使用ガイド

コードベース分析のワークフロー

  1. index_repositoryを使用して分析するインデックス リポジトリ

  2. get_repository_infoを使用してインデックス作成ステータスを確認し、処理が完了していることを確認します。

  3. query_repositoryを使用して自然言語でリポジトリをクエリする

  4. search_repositoryを使用して機能や概念に関連する特定のファイルを検索します

会話コンテキストのセッション管理

任意のクライアント (Smishery を含む) を介して Greptile MCP サーバーと対話する場合、会話のコンテキストを維持するために適切なセッション管理が重要です。

  1. 会話の開始時に一意のセッションIDを生成する

  2. 関連するすべてのフォローアップクエリに同じセッションIDを再利用します

  3. 新しい会話を開始するときに新しいセッション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 (文字列): 所有者/リポジトリ形式のリポジトリ (例: "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 (文字列、オプション): 会話を続けるためのセッションID

  • stream (boolean, オプション): レスポンスをストリームするかどうか

  • 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 (文字列、オプション): 会話を続けるためのセッションID

  • genius (ブール値、オプション):拡張検索機能を使用するかどうか

例:

// 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 (文字列): 所有者/リポジトリ形式のリポジトリ

  • 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 --reload

3. コマンドラインコードクエリツール

#!/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. 認証失敗

症状: Repository not found with configured credentials 401 Unauthorizedまたは「リポジトリが見つかりません」というエラーが発生します。

ソリューション

  • Greptile APIキーが有効であり、 .envファイルに正しく設定されていることを確認します。

  • GitHub/GitLab トークンの有効期限が切れていないか確認してください (通常、一定期間後に有効期限が切れます)

  • GitHub/GitLabトークンにリポジトリにアクセスするためのrepoスコープがあることを確認してください

  • GitHub APIを使用してGitHubトークンを直接テストし、動作を確認します。

GitHubトークンのテスト

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ネットワーク構成で必要な接続が許可されているかどうかを確認する

ログとデバッグ

より詳細なログ記録を有効にするには、次の環境変数を設定します。

# Add to your .env file
DEBUG=true
LOG_LEVEL=debug

特定の MCP 相互作用のトラブルシューティングについては、MCP サーバー ログを調べます。

# Run with enhanced logging
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

パフォーマンスチューニング

実稼働環境での展開では、次のパフォーマンスの最適化を検討してください。

  1. ワーカー構成: Uvicorn で SSE トランスポートを使用する場合は、適切なワーカー数を構成します。

    # For CPU-bound applications: workers = 1-2 × CPU cores
    uvicorn src.main:app --workers 4
  2. タイムアウト設定: 大規模なリポジトリのタイムアウトを調整します。

    # Add to .env
    GREPTILE_TIMEOUT=120.0  # Default is 60.0 seconds
  3. メモリの最適化: 大規模な展開では、コンテナ リソースの制限を考慮してください。

    docker run --rm --env-file .env -p 8050:8050 --memory="1g" --cpus="1.0" greptile-mcp

貢献

貢献を歓迎します!お気軽にプルリクエストを送信してください。

  1. リポジトリをフォークする

  2. 機能ブランチを作成します( git checkout -b feature/amazing-feature

  3. 変更をコミットします ( git commit -m 'Add some amazing feature' )

  4. ブランチにプッシュする ( git push origin feature/amazing-feature )

  5. プルリクエストを開く

開発セットアップ

開発の場合は、追加の依存関係をインストールします。

pip install -e ".[dev]"

テストを実行します:

pytest

ライセンス

このプロジェクトは MIT ライセンスに基づいてライセンスされています - 詳細については LICENSE ファイルを参照してください。


作成者 ( https://github.com/sosacrazy126 )

Install Server
A
security – no known vulnerabilities
A
license - permissive license
A
quality - confirmed to work

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sosacrazy126/greptile-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server