Skip to main content
Glama

query_repository

Query code repositories using natural language to get detailed answers with code references. Understand codebases by asking questions about repositories from GitHub or GitLab.

Instructions

Query repositories using natural language to get detailed answers with code references

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesNatural language query about the codebase
repositoriesNoList of repositories to query
session_idNoSession ID for conversation continuity (auto-generated if not provided)
streamNoEnable streaming response
geniusNoUse enhanced query capabilities
timeoutNoRequest timeout in milliseconds
previous_messagesNoPrevious conversation messages for context

Implementation Reference

  • Main MCP tool handler for 'query_repository'. Processes arguments, handles session management, streaming/non-streaming logic, error checking, and delegates to GreptileClient.queryRepositories.
    private async handleQueryRepository(
      args: unknown
    ): Promise<{ content: Array<{ type: string; text: string }> }> {
      if (!this.greptileClient) {
        return {
          content: [
            {
              type: 'text',
              text: createErrorResponse(
                'Cannot query repository: Missing environment variables. Use greptile_env_check for setup guidance.',
                'Configuration Error',
                undefined
              ),
            },
          ],
        };
      }
    
      const {
        query,
        repositories = [],
        session_id,
        stream = false,
        genius = true,
        timeout,
        previous_messages = [],
      } = args as any;
    
      // Generate session ID if not provided
      const sessionId = session_id || generateSessionId();
    
      // Prepare messages array
      const messages = [...previous_messages, { role: 'user' as const, content: query }];
    
      if (stream) {
        // Handle streaming response
        const streamResults: string[] = [];
        const streamingResponse = await this.greptileClient.queryRepositories(
          messages,
          repositories,
          sessionId,
          true,
          genius,
          timeout
        );
    
        for await (const chunk of streamingResponse as AsyncIterable<any>) {
          if (chunk.type === 'text' && chunk.content) {
            streamResults.push(chunk.content);
          }
        }
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  message: streamResults.join(''),
                  session_id: sessionId,
                  streamed: true,
                },
                null,
                2
              ),
            },
          ],
        };
      } else {
        // Handle regular response
        const result = await this.greptileClient.queryRepositories(
          messages,
          repositories,
          sessionId,
          false,
          genius,
          timeout
        );
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({ ...result, session_id: sessionId }, null, 2),
            },
          ],
        };
      }
    }
  • src/server.ts:136-194 (registration)
    MCP tool registration including name, description, and input schema definition in the ListTools handler.
      name: 'query_repository',
      description:
        'Query repositories using natural language to get detailed answers with code references',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'Natural language query about the codebase',
          },
          repositories: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                remote: { type: 'string', enum: ['github', 'gitlab'] },
                repository: { type: 'string' },
                branch: { type: 'string' },
              },
              required: ['remote', 'repository', 'branch'],
            },
            description: 'List of repositories to query',
          },
          session_id: {
            type: 'string',
            description:
              'Session ID for conversation continuity (auto-generated if not provided)',
          },
          stream: {
            type: 'boolean',
            description: 'Enable streaming response',
            default: false,
          },
          genius: {
            type: 'boolean',
            description: 'Use enhanced query capabilities',
            default: true,
          },
          timeout: {
            type: 'number',
            description: 'Request timeout in milliseconds',
            default: 60000,
          },
          previous_messages: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                role: { type: 'string', enum: ['user', 'assistant'] },
                content: { type: 'string' },
              },
              required: ['role', 'content'],
            },
            description: 'Previous conversation messages for context',
          },
        },
        required: ['query'],
      },
    },
  • TypeScript interface defining the input shape for query_repository tool, matching the runtime schema.
    export interface QueryRepositoryInput {
      query: string;
      repositories?: Repository[];
      session_id?: string;
      stream?: boolean;
      genius?: boolean;
      timeout?: number;
      previous_messages?: QueryMessage[];
    }
  • Core GreptileClient method implementing non-streaming query logic by making POST request to Greptile API /query endpoint.
    async queryRepositories(
      messages: QueryMessage[],
      repositories: Repository[],
      sessionId?: string,
      stream: boolean = false,
      genius: boolean = true,
      timeout?: number
    ): Promise<QueryResponse | AsyncIterable<StreamingChunk>> {
      if (stream) {
        return this.streamQueryRepositories(messages, repositories, sessionId, genius, timeout);
      }
    
      const url = `${this.baseUrl}/query`;
      const payload: Record<string, unknown> = {
        messages,
        stream: false,
        genius,
      };
    
      if (repositories.length > 0) {
        payload.repositories = repositories;
      }
      if (sessionId) {
        payload.sessionId = sessionId;
      }
    
      const response = await this.makeRequest('POST', url, payload, timeout);
      return response as QueryResponse;
    }
  • GreptileClient streaming query implementation using Server-Sent Events (SSE), parsing chunks and yielding standardized StreamingChunk objects.
    async *streamQueryRepositories(
      messages: QueryMessage[],
      repositories: Repository[],
      sessionId?: string,
      genius: boolean = true,
      timeout?: number
    ): AsyncIterable<StreamingChunk> {
      const url = `${this.baseUrl}/query`;
      const payload: Record<string, unknown> = {
        messages,
        stream: true,
        genius,
      };
    
      if (repositories.length > 0) {
        payload.repositories = repositories;
      }
      if (sessionId) {
        payload.sessionId = sessionId;
      }
    
      const streamHeaders = {
        ...this.headers,
        Accept: 'text/event-stream',
        'Cache-Control': 'no-cache',
      };
    
      const controller = new AbortController();
      const timeoutId = timeout ? setTimeout(() => controller.abort(), timeout) : null;
    
      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: streamHeaders,
          body: JSON.stringify(payload),
          signal: controller.signal,
        });
    
        if (!response.ok) {
          throw this.createError(`HTTP ${response.status}: ${response.statusText}`, response.status);
        }
    
        if (!response.body) {
          throw this.createError('No response body for streaming request');
        }
    
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
    
        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;
    
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';
    
            for (const line of lines) {
              if (line.trim() && line.startsWith('data: ')) {
                const data = line.slice(6);
                const chunk = safeJsonParse(data, null);
    
                if (chunk) {
                  const processedChunk = this.processStreamChunk(chunk);
                  if (processedChunk) {
                    yield processedChunk;
                  }
                }
              }
            }
          }
        } finally {
          reader.releaseLock();
        }
      } finally {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'natural language querying' and 'detailed answers with code references,' but fails to describe critical behaviors such as authentication requirements, rate limits, error handling, or what constitutes a 'detailed answer.' For a complex tool with 7 parameters, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that clearly states the tool's core functionality without unnecessary details. It's front-loaded with the main purpose and avoids redundancy, making it easy for an agent to parse quickly. Every word earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (7 parameters, no annotations, no output schema), the description is insufficient. It lacks information on behavioral traits, output format, error conditions, and how it differs from siblings. For a query tool that likely returns structured data, the absence of output details and usage context makes it incomplete for effective agent operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, so each parameter is documented in the schema itself. The description adds no additional semantic context beyond implying natural language input for the 'query' parameter. This meets the baseline of 3, as the schema handles the heavy lifting, but the description doesn't enhance understanding of parameter usage or interactions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Query repositories using natural language to get detailed answers with code references.' It specifies the action (query), resource (repositories), and outcome (detailed answers with code references). However, it doesn't explicitly differentiate from sibling tools like 'get_repository_info' or 'index_repository', which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'get_repository_info' for metadata or 'index_repository' for preparation, nor does it specify scenarios where this tool is preferred. This lack of comparative context leaves the agent without clear usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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