Skip to content

Expose Repository Search and Read as Composable MCP Tools with Policy Authorization #2798

Closed

Description

@propr-dev

Context

The ProPR MCP server registers tools that permit autonomous coding agents and chat clients to inspect and drive the platform. Existing context tools in packages/api/mcp/toolsContext.ts provide high-level summary trees (get_repository_context) and entity name resolution (resolve_reference), but do not allow an agent to search repository code or read file contents. Because the GitHub connector's get_file_contents does not surface file bodies inline, an MCP client cannot perform a search-then-read loop. This task registers search_repository_files and read_repository_file as first-class, read-only MCP tools in packages/api/mcp/toolsContext.ts, enforcing repository grant authorization, standard input validation schemas, and error envelopes.

Requirements

  1. Tool Registration in packages/api/mcp/toolsContext.ts:
    • Register search_repository_files:
      • Parameters: repository (repositorySchema), query (1-1000 chars), mode ('semantic' | 'literal', default 'semantic'), branch (optional string), ref (optional string), path (optional subpath string), caseSensitive (optional boolean), and ...pageShape (offset, limit).
      • scope: 'read', readOnly: true.
      • Description clearly explaining that semantic uses index-based planner relevance while literal performs exact string grep across the git tree at the specified ref.
    • Register read_repository_file:
      • Parameters: repository (repositorySchema), path (1-1024 chars), branch (optional string), ref (optional string), startLine (int >= 1, default 1), endLine (optional int >= 1), maxLines (int 1-1000, default 800), maxBytes (int 1-500000, default 120000).
      • scope: 'read', readOnly: true.
      • Description explaining line-chunked reading without local cloning.
  2. Security & Authorization:
    • Call await policy.repository(principal, args.repository) at the start of both handlers. This ensures the repository is configured, enabled in the instance, explicitly granted to the principal, and accessible via the user's GitHub credential.
    • Reject paths with directory traversal (..), leading slashes, or backslashes before running git operations.
  3. Execution & Error Mapping:
    • Forward authenticated tokens (principal.user.accessToken or installation token) to searchRepositoryFiles and readRepositoryFileContent.
    • Wrap domain errors in McpError envelopes with stable error codes:
      • 400 INVALID_PATH
      • 400 BINARY_FILE
      • 404 FILE_NOT_FOUND
      • 403 REPOSITORY_FORBIDDEN
    • Wrap successful results in ok({ ... }).

Implementation Specification

  • File: packages/api/mcp/toolsContext.ts (modify)

Acceptance Criteria

  • search_repository_files and read_repository_file are registered in the tool catalog with scope: 'read' and readOnly: true.
  • search_repository_files accepts mode: 'semantic' and mode: 'literal', returning matching paths without dumping full file contents.
  • read_repository_file returns bounded file contents with startLine, endLine, totalLines, and truncated indicator.
  • Path traversal returns 400 INVALID_PATH, binary files return 400 BINARY_FILE, missing files return 404 FILE_NOT_FOUND.
  • Inaccessible repositories return 403 REPOSITORY_FORBIDDEN.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    This task exposes the core repository retrieval engine over the Model Context Protocol (MCP) by registering two lightweight, composable tools in packages/api/mcp/toolsContext.ts: search_repository_files and read_repository_file. We deliberately keep these tools separate rather than combining them into one monolithic call so that AI agent clients can drive flexible search-then-read loops without paying token costs for unneeded file bodies. Both tools inherit the standard ProPR MCP security architecture: they enforce repository grant validation via policy.repository(principal, args.repository), declare scope: 'read' and readOnly: true, validate input with Zod schemas, and map domain errors to stable McpError envelopes.

    File: packages/api/mcp/toolsContext.ts

    Why this file: toolsContext.ts manages all repository-inspection tools on the MCP surface (alongside resolve_reference and get_repository_context). Adding search_repository_files and read_repository_file here keeps repository reading and navigation tools grouped logically, ensuring they receive policy and db dependencies from the tool catalog factory.

    --- a/packages/api/mcp/toolsContext.ts
    +++ b/packages/api/mcp/toolsContext.ts
    @@ -1,4 +1,7 @@
     import { z } from 'zod';
    -import { loadMonitoredReposRaw } from '@propr/core';
    +import {
    +  loadMonitoredReposRaw,
    +  searchRepositoryFiles,
    +  readRepositoryFileContent,
    +  getGitHubInstallationToken,
    +} from '@propr/core';
     import { type McpTool, type ToolDeps, repositorySchema, pageShape, ok } from './tools.js';
     import { McpError } from './config.js';
     
    @@ -59,2 +62,112 @@
         } });
    +  tools.push({
    +    name: 'search_repository_files',
    +    description: 'Search repository files using semantic relevance matching (via the repository index used by the planner) or literal grep across the git tree. Returns matching file paths and ranking without dumping full file contents.',
    +    scope: 'read',
    +    readOnly: true,
    +    schema: z.object({
    +      repository: repositorySchema,
    +      query: z.string().min(1).max(1000).describe('Search query or prompt keywords'),
    +      mode: z.enum(['semantic', 'literal']).default('semantic').describe('Search mode: "semantic" uses planner index relevance; "literal" runs exact string grep across the git tree.'),
    +      branch: z.string().min(1).max(255).optional().describe('Branch name (defaults to repository default branch or HEAD)'),
    +      ref: z.string().min(1).max(255).optional().describe('Git ref, branch, or commit SHA'),
    +      path: z.string().max(1024).optional().describe('Optional repository-relative subpath prefix to filter search results'),
    +      caseSensitive: z.boolean().default(false).optional().describe('Case-sensitive matching for literal search mode'),
    +      ...pageShape,
    +    }).strict(),
    +    run: async ({ principal, args }) => {
    +      // Enforce repository grant and permissions before accessing repository data. Calling policy.repository ensures the repo is in the principal's grant and has valid GitHub API permissions.
    +      await policy.repository(principal, args.repository);
    +
    +      // Resolve credentials: prefer GitHub installation token, fall back to principal access token. This allows both desktop user sessions and automated background agents to access authorized private repositories.
    +      let authToken = principal.user?.accessToken;
    +      try {
    +        const installToken = await getGitHubInstallationToken();
    +        if (installToken) authToken = installToken;
    +      } catch {
    +        // Fallback to user's verified session token
    +      }
    +
    +      try {
    +        const result = await searchRepositoryFiles({
    +          repository: args.repository,
    +          query: args.query,
    +          mode: args.mode,
    +          branch: args.branch,
    +          ref: args.ref,
    +          path: args.path,
    +          caseSensitive: args.caseSensitive,
    +          offset: args.offset,
    +          limit: args.limit,
    +          authToken,
    +        });
    +        return ok(result);
    +      } catch (error: any) {
    +        if (error instanceof McpError) throw error;
    +        if (error.code === 'INVALID_PATH' || error.status === 400) {
    +          throw new McpError('INVALID_PATH', error.message, 400);
    +        }
    +        throw new McpError('SEARCH_FAILED', error.message || 'Repository file search failed', error.status || 500);
    +      }
    +    },
    +  });
    +  tools.push({
    +    name: 'read_repository_file',
    +    description: 'Read bounded line chunks from a repository file at a given ref/branch without cloning locally. Supports startLine, endLine, maxLines, and maxBytes to prevent payload overruns.',
    +    scope: 'read',
    +    readOnly: true,
    +    schema: z.object({
    +      repository: repositorySchema,
    +      path: z.string().min(1).max(1024).describe('Repository-relative file path'),
    +      branch: z.string().min(1).max(255).optional().describe('Branch name (defaults to repository default branch or HEAD)'),
    +      ref: z.string().min(1).max(255).optional().describe('Git ref, branch, or commit SHA'),
    +      startLine: z.number().int().min(1).default(1).describe('1-indexed starting line number'),
    +      endLine: z.number().int().min(1).optional().describe('1-indexed ending line number (inclusive)'),
    +      maxLines: z.number().int().min(1).max(1000).default(800).optional().describe('Maximum number of lines to return'),
    +      maxBytes: z.number().int().min(1).max(500000).default(120000).optional().describe('Maximum bytes of content to return'),
    +    }).strict(),
    +    run: async ({ principal, args }) => {
    +      // Validate path early to fail fast on directory traversal attempts before running git operations. This protects against malicious inputs attempting to escape the repository root.
    +      if (args.path.startsWith('/') || args.path.split('/').includes('..') || args.path.includes('\\')) {
    +        throw new McpError('INVALID_PATH', 'Use a repository-relative path without directory traversal.');
    +      }
    +
    +      // Verify repository authorization against principal's OAuth grant
    +      await policy.repository(principal, args.repository);
    +
    +      let authToken = principal.user?.accessToken;
    +      try {
    +        const installToken = await getGitHubInstallationToken();
    +        if (installToken) authToken = installToken;
    +      } catch {
    +        // Fallback to user token
    +      }
    +
    +      try {
    +        const result = await readRepositoryFileContent({
    +          repository: args.repository,
    +          path: args.path,
    +          branch: args.branch,
    +          ref: args.ref,
    +          startLine: args.startLine,
    +          endLine: args.endLine,
    +          maxLines: args.maxLines,
    +          maxBytes: args.maxBytes,
    +          authToken,
    +        });
    +        return ok(result);
    +      } catch (error: any) {
    +        // Map domain errors to stable McpError codes (FILE_NOT_FOUND, BINARY_FILE, INVALID_PATH) to maintain a consistent error envelope across all MCP endpoints.
    +        if (error instanceof McpError) throw error;
    +        if (error.code === 'FILE_NOT_FOUND' || error.status === 404) {
    +          throw new McpError('FILE_NOT_FOUND', error.message || `File "${args.path}" was not found at ref.`, 404);
    +        }
    +        if (error.code === 'BINARY_FILE' || error.status === 400) {
    +          throw new McpError('BINARY_FILE', error.message || 'Binary files cannot be read over MCP.', 400);
    +        }
    +        if (error.code === 'INVALID_PATH') {
    +          throw new McpError('INVALID_PATH', error.message, 400);
    +        }
    +        throw new McpError('FILE_READ_FAILED', error.message || 'Failed to read repository file', error.status || 500);
    +      }
    +    },
    +  });
     }
  2. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2798/claude-opus-5-5-expose-repository-search--20261006-1503-b8h
    • Base Branch: 2797-epic-repository-search-sgj
    • Worktree: issue-2798-20261006-1503-claude-opus-5-5-b8h

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions