Skip to content

API Reference parrot_tools.gittoolkit

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_tools.gittoolkit

View source

Git/GitHub toolkit inspired by :mod:parrot.tools.jiratoolkit.

This toolkit focuses on two complementary workflows that frequently appear in software review loops:

  • producing a git apply compatible patch from pieces of code supplied by an agent or user; and
  • turning those code snippets into an actionable GitHub pull request via the public REST API.

The implementation deliberately mirrors the structure of JiraToolkit—async public methods automatically become tools thanks to the AbstractToolkit base class—so that it can be dropped into existing agent configurations with minimal friction.

Only standard library modules (plus :mod:requests, :mod:pydantic, which are already dependencies of Parrot, and PyGithub>=2.1 for GitHub App authentication) are required.

Class AddPRCommentInput

Input payload for add_pr_comment.

Fields:

Field Type Default Description
pr_number int Pull request number on the repository.
body str Comment body in Markdown.
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.

Class ComparePRVersionsInput

Input payload for compare_pr_versions.

Fields:

Field Type Default Description
pr_number int Pull request number on the repository.
path str File path to compare between the PR base and head refs.
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.

Class CompareVersionsResult

Return payload for compare_pr_versions.

Fields:

Field Type Default Description
repository str Repository in 'owner/name' format.
pr_number int Pull request number.
path str File path that was compared.
base_sha str Full commit SHA of the PR base ref.
head_sha str Full commit SHA of the PR head ref.
base FileContentResult File content at the base ref (before the PR's changes).
head FileContentResult File content at the head ref (after the PR's changes).

Class ContributorStats

Aggregated stats for a single contributor across the repository's history.

Fields:

Field Type Default Description
login Optional[str] GitHub login, or None when the commit email is not linked to an account.
avatar_url Optional[str] None Avatar URL from the GitHub user object (None for anonymous).
total_commits int All-time commit count for this contributor.
weeks List[ContributorWeek] Per-week breakdown — most recent last (GitHub ordering).

Class ContributorWeek

One week's slice of a contributor's activity.

Mirrors the GitHub weeks[] entry from GET /repos/{owner}/{repo}/stats/contributors.

Fields:

Field Type Default Description
week_start datetime Sunday 00:00 UTC that begins this week (GitHub epoch converted to UTC).
additions int Lines added in the week.
deletions int Lines deleted in the week (non-negative).
commits int Commit count for the week.

Class CreatePullRequestInput

Input payload for create_pull_request.

Fields:

Field Type Default Description
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.
title str Pull request title
body Optional[str] None Pull request description
base_branch Optional[str] None Branch into which the changes should merge.
head_branch Optional[str] None Branch name to create and push changes onto.
commit_message Optional[str] None Commit message used for the updates (defaults to title).
files List[GitHubFileChange] List of file updates that compose the pull request.
draft bool False Create the pull request as a draft if true.
labels Optional[List[str]] None Optional labels to apply after PR creation.

Class FileContentResult

Return payload for get_file_content_at_ref.

Fields:

Field Type Default Description
exists bool True when the file was found at the given ref; False on 404.
path str File path as requested.
ref str Ref (branch, tag, or SHA) that was used to resolve the file.
repository str Repository in 'owner/name' format.
content Optional[str] None Decoded UTF-8 text content of the file, or None when exists=False or error is set.
encoding Optional[str] None Content encoding: 'utf-8' for text files or 'base64' for binary blobs.
size_bytes Optional[int] None Raw file size in bytes as reported by the GitHub Contents API.
sha Optional[str] None Git blob SHA — used as the cache key for _FileBlobCache.
commit_author Optional[str] None GitHub login of the author of the most recent commit that touched this file at ref.
truncated bool False True when start_line/end_line slicing was applied to the content.
error Optional[str] None Error indicator. 'file_too_large' when the blob exceeds GitHub's 1 MB limit; 'rate_limited' when the API quota is exhausted; None on success.

Class GeneratePatchInput

Input payload for generate_git_apply_patch.

Fields:

Field Type Default Description
files List[GitPatchFile] Collection of file changes that should be turned into a unified diff.
context_lines int 3 How many context lines to include in the diff output.
include_apply_snippet bool True If true, include a ready-to-run git-apply heredoc snippet.

Class GetCodeFrequencyInput

Input payload for get_code_frequency.

Fields:

Field Type Default Description
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.

Class GetCommitActivityInput

Input payload for get_weekly_commit_activity.

Fields:

Field Type Default Description
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.

Class GetContributorStatsInput

Input payload for get_contributor_stats.

Fields:

Field Type Default Description
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.

Class GetFileContentInput

Input payload for get_file_content_at_ref.

Fields:

Field Type Default Description
path str File path inside the repository, e.g. 'src/parrot/bots/agent.py'.
ref str Branch name, tag, or commit SHA at which to retrieve the file.
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.
start_line Optional[int] None First line to return (1-indexed). When provided together with end_line, only that slice is returned and truncated=True is set on the result.
end_line Optional[int] None Last line to return (1-indexed, inclusive). Must be >= start_line when both are set.

Class GetPullRequestDiffInput

Input payload for get_pull_request_diff.

Fields:

Field Type Default Description
pr_number int Pull request number on the repository.
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.
max_bytes int 50000 Truncate the diff to at most this many bytes (0 disables truncation).

Class GetPullRequestInput

Input payload for get_pull_request.

Fields:

Field Type Default Description
pr_number int Pull request number on the repository.
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.

Class GitHubFileChange

Description of a file mutation when creating a pull request.

Fields:

Field Type Default Description
path str File path inside the repository.
content Optional[str] None New file content. Leave None to delete a file.
encoding Literal['utf-8', 'base64'] 'utf-8' Encoding used for content.
message Optional[str] None Optional commit message just for this file change.
change_type Literal['modify', 'add', 'delete'] 'modify' Type of change performed on the file.

Class GitPatchFile

Represents a single file change for patch generation.

Fields:

Field Type Default Description
path str Path to the file inside the repository.
change_type Literal['modify', 'add', 'delete'] 'modify' Type of change represented by this patch fragment.
original Optional[str] None Original file contents relevant to the change.
updated Optional[str] None Updated file contents to apply.
from_path Optional[str] None Override the 'from' path in the generated diff.
to_path Optional[str] None Override the 'to' path in the generated diff.

Class GitToolkit

Toolkit dedicated to Git patch generation and GitHub pull requests.

Parameter Type Default Description
default_repository Optional[str] None Default repo in owner/name format.
default_branch str 'main' Fallback branch for pull requests.
github_token Optional[str] None PAT for GitHub API calls (required in pat mode).
auth_type Literal['pat', 'github_app'] 'pat' Authentication backend — 'pat' (default) or 'github_app'.
app_id Optional[int] None GitHub App ID (required when auth_type='github_app').
installation_id Optional[int] None Installation ID for the org/account the App is installed in (required when auth_type='github_app').
private_key Optional[str] None PEM contents of the App's private key. Mutually exclusive with private_key_path.
private_key_path Optional[str] None Filesystem path to the App's private key PEM. Mutually exclusive with private_key.
repositories Optional[Dict[str, Union[RepositoryCredential, dict]]] None Optional named registry mapping an alias to that repository's credentials (RepositoryCredential or an equivalent dict). Tools may reference a repository by its alias or by its raw owner/name slug. Registry entries are explicit-config only — they do NOT inherit GITHUB_* env vars. Passing a "default" alias here while the legacy default_repository argument is also set raises, to avoid ambiguity.
**kwargs Any {} Forwarded to the base class.

Attributes:

Attribute Type Description
auth_type Literal['pat', 'github_app']
app_id Optional[int]
installation_id Optional[int]

Method GitToolkit.generate_git_apply_patch

Create a unified diff (and optional git apply snippet) from code blocks.

generate_git_apply_patch(files: List[GitPatchFile], context_lines: int = 3, include_apply_snippet: bool = True) -> Dict[str, Any]

Parameter Type Default Description
files List[GitPatchFile]
context_lines int 3
include_apply_snippet bool True

Returns: Dict[str, Any]

Method GitToolkit.create_pull_request

Create a GitHub pull request with the supplied file updates.

create_pull_request(repository: Optional[str], title: str, body: Optional[str], base_branch: Optional[str], head_branch: Optional[str], commit_message: Optional[str], files: List[GitHubFileChange], draft: bool = False, labels: Optional[List[str]] = None) -> Dict[str, Any]

Parameter Type Default Description
repository Optional[str]
title str
body Optional[str]
base_branch Optional[str]
head_branch Optional[str]
commit_message Optional[str]
files List[GitHubFileChange]
draft bool False
labels Optional[List[str]] None

Returns: Dict[str, Any]

Method GitToolkit.clone_repo

Clone repository to dest_dir.

Uses the configured PAT / GitHub-App token (or the gh CLI when present) for private repos. Idempotent: if dest_dir already holds a git clone, delegates to :meth:pull_repo instead of re-cloning.

clone_repo(repository: str, dest_dir: str, branch: Optional[str] = None, *, private: bool = False, depth: Optional[int] = None, timeout: Optional[float] = None, prefer_gh: bool = True) -> Dict[str, Any]

Parameter Type Default Description
repository str An alias from the configured registry, an owner/name slug, or a full clone URL.
dest_dir str Destination directory for the clone.
branch Optional[str] None Optional branch to clone (--branch).
private bool False When True, authenticate the clone (gh or token-in-URL).
depth Optional[int] None Optional shallow-clone depth (--depth).
timeout Optional[float] None Optional subprocess timeout in seconds.
prefer_gh bool True Whether to prefer gh repo clone for private clones.

Returns: Dict[str, Any] — {"path", "repository", "branch", "updated"}. Never contains a token.

Raises:

  • GitToolkitError — If the clone/pull fails (stderr is token-scrubbed).

Method GitToolkit.pull_repo

Fast-forward an existing clone at repo_path to branch.

pull_repo(repo_path: str, branch: Optional[str] = None, *, timeout: Optional[float] = None, private: bool = False) -> Dict[str, Any]

Parameter Type Default Description
repo_path str Path to an existing git clone.
branch Optional[str] None Optional branch to pull (origin <branch>); defaults to the clone's current upstream.
timeout Optional[float] None Optional subprocess timeout in seconds.
private bool False Authenticate through the subprocess environment (git >= 2.31) and first rewrite a credential-bearing origin URL (left by an earlier clone) to its clean form.

Returns: Dict[str, Any] — {"path", "branch", "updated"}. Never contains a token.

Raises:

  • GitToolkitError — If repo_path is not a clone or the pull fails.

Method GitToolkit.get_pull_request

Fetch metadata for a GitHub pull request by number.

get_pull_request(pr_number: int, repository: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
pr_number int
repository Optional[str] None

Returns: Dict[str, Any]

Method GitToolkit.list_pull_requests

List pull requests on a repository, defaulting to open ones.

list_pull_requests(repository: Optional[str] = None, state: Literal['open', 'closed', 'all'] = 'open', per_page: int = 100) -> List[Dict[str, Any]]

Parameter Type Default Description
repository Optional[str] None
state Literal['open', 'closed', 'all'] 'open'
per_page int 100

Returns: List[Dict[str, Any]]

Method GitToolkit.get_pull_request_diff

Return the raw unified diff of a pull request, truncated to max_bytes.

get_pull_request_diff(pr_number: int, repository: Optional[str] = None, max_bytes: int = 50000) -> Dict[str, Any]

Parameter Type Default Description
pr_number int
repository Optional[str] None
max_bytes int 50000

Returns: Dict[str, Any]

Method GitToolkit.add_pr_comment

Add an issue-style comment to a pull request.

add_pr_comment(pr_number: int, body: str, repository: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
pr_number int
body str
repository Optional[str] None

Returns: Dict[str, Any]

Method GitToolkit.submit_pr_review

Submit a pull-request review (approve, request-changes or comment).

submit_pr_review(pr_number: int, event: Literal['APPROVE', 'REQUEST_CHANGES', 'COMMENT'], body: str, repository: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
pr_number int
event Literal['APPROVE', 'REQUEST_CHANGES', 'COMMENT']
body str
repository Optional[str] None

Returns: Dict[str, Any]

Method GitToolkit.list_pull_request_files

List changed files, including patch when supplied by GitHub.

list_pull_request_files(pr_number: int, repository: Optional[str] = None, max_items: int = 300) -> List[Dict[str, Any]]

Parameter Type Default Description
pr_number int
repository Optional[str] None
max_items int 300

Returns: List[Dict[str, Any]]

Method GitToolkit.list_pull_request_comments

List issue-style comments with author identity and Bot/User type.

list_pull_request_comments(pr_number: int, repository: Optional[str] = None, max_items: int = 300) -> List[Dict[str, Any]]

Parameter Type Default Description
pr_number int
repository Optional[str] None
max_items int 300

Returns: List[Dict[str, Any]]

Method GitToolkit.list_pull_request_reviews

List PR review summaries with state and commit identity.

list_pull_request_reviews(pr_number: int, repository: Optional[str] = None, max_items: int = 300) -> List[Dict[str, Any]]

Parameter Type Default Description
pr_number int
repository Optional[str] None
max_items int 300

Returns: List[Dict[str, Any]]

Method GitToolkit.list_pull_request_review_comments

List inline comments, locations and reply relationships.

list_pull_request_review_comments(pr_number: int, repository: Optional[str] = None, max_items: int = 300) -> List[Dict[str, Any]]

Parameter Type Default Description
pr_number int
repository Optional[str] None
max_items int 300

Returns: List[Dict[str, Any]]

Method GitToolkit.get_pr_checks

Return the CI checks reported for a pull request's head commit.

Merges the Checks API (check-runs) with the legacy Commit Status API, because a repository may use either or both, and normalizes every entry to state in success|failure|pending alongside the raw GitHub fields. head_sha skips the extra PR lookup when the caller already knows it.

The two APIs sit behind independent token permissions, so a 403/404 on one does not discard the other: the denial is listed in denied and explained in reason, and available is False only when BOTH were refused — "we do not know" must never read as "green".

get_pr_checks(pr_number: int, repository: Optional[str] = None, head_sha: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
pr_number int
repository Optional[str] None
head_sha Optional[str] None

Returns: Dict[str, Any]

Method GitToolkit.convert_pr_to_draft

Convert an open pull request into a draft so it cannot be merged.

Returns status in converted|already_draft|not_open. Needs the GraphQL mutation (REST has no writable draft field), so the token must carry the same pull_requests: write permission used to submit reviews.

convert_pr_to_draft(pr_number: int, repository: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
pr_number int
repository Optional[str] None

Returns: Dict[str, Any]

Method GitToolkit.ensure_webhook

Ensure a GitHub webhook pointing at webhook_url exists on the repo.

Idempotent. Falls back gracefully when GitHub refuses the hooks endpoint (status "no_permission") so callers can run in hybrid mode (auto when allowed, manual otherwise). That refusal is not always a missing scope: repository webhooks require the admin role on the repo, and a fine-grained token can never exceed its owner's role, so the result also carries status_code, api_message and required_permission for the operator-facing log.

ensure_webhook(webhook_url: str, repository: Optional[str] = None, secret: Optional[str] = None, events: Optional[List[str]] = None) -> Dict[str, Any]

Parameter Type Default Description
webhook_url str
repository Optional[str] None
secret Optional[str] None
events Optional[List[str]] None

Returns: Dict[str, Any]

Method GitToolkit.get_file_content_at_ref

Return the full or sliced contents of a file at a given git ref.

Fetches the file at the specified ref (branch name, tag, or full commit SHA) from the GitHub Contents API. The blob is stored in an in-process SHA-keyed cache so that repeated requests for the same ref do not incur extra HTTP round-trips within a single review session.

Cache lookup order for blob content:

  1. Redis (checked here in the async wrapper before calling the sync helper)
  2. In-process LRU (checked inside the sync helper)
  3. Base64 decode from the GitHub Contents API response

The Contents API metadata call (which provides the blob SHA) is always made to resolve the SHA before the cache can be checked. This is unavoidable — the SHA is not known until the metadata is fetched.

Use this tool when the PR diff shows a change to a function or class but the hunk is too small to judge correctness without seeing the full file body. Prefer start_line / end_line on large files to stay within the LLM context budget.

Example::

result = await toolkit.get_file_content_at_ref(
    path="parrot/bots/agent.py",
    ref="main",
    start_line=100,
    end_line=150,
)
if result.exists and result.content:
    print(result.content)

get_file_content_at_ref(path: str, ref: str, repository: Optional[str] = None, start_line: Optional[int] = None, end_line: Optional[int] = None) -> 'FileContentResult'

Parameter Type Default Description
path str File path inside the repository (e.g. "src/parrot/bots/agent.py").
ref str Branch name, tag, or commit SHA at which to retrieve the file.
repository Optional[str] None Repository in owner/name format. Uses the toolkit default when omitted.
start_line Optional[int] None First line to return (1-indexed). When provided without end_line, returns from this line to end-of-file.
end_line Optional[int] None Last line to return (1-indexed, inclusive). When provided without start_line, returns from line 1 to this line.

Returns: 'FileContentResult' — class:FileContentResult with exists=True and content set on success; exists=False when the file is not found; error='file_too_large' when the blob exceeds GitHub's 1 MB limit.

Method GitToolkit.list_repo_directory

List files and subdirectories at path for an explicit git ref.

list_repo_directory(path: str, ref: str, repository: Optional[str] = None) -> 'RepoDirectoryListing'

Parameter Type Default Description
path str
ref str
repository Optional[str] None

Returns: 'RepoDirectoryListing'

Method GitToolkit.compare_pr_versions

Return the base and head versions of a single file in a pull request.

Fetches the full content of path at both the PR's base commit SHA and its head commit SHA. Both calls route through :meth:_FileBlobCache so that multiple reviews of the same PR only hit GitHub once per (repository, blob SHA) pair.

Use this tool when the PR diff hunk is too small to judge whether a refactored function or class is correct; viewing the full before/after bodies often reveals intent that a small hunk obscures.

Example::

diff = await toolkit.compare_pr_versions(pr_number=42, path="utils.py")
print("Before:", diff.base.content)
print("After:", diff.head.content)

compare_pr_versions(pr_number: int, path: str, repository: Optional[str] = None) -> 'CompareVersionsResult'

Parameter Type Default Description
pr_number int Pull request number (must be >= 1).
path str File path to compare (e.g. "src/utils.py").
repository Optional[str] None Repository in owner/name format. Uses the toolkit default when omitted.

Returns: 'CompareVersionsResult' — class:CompareVersionsResult with base and head class:FileContentResult objects. When the file was added in the PR, base.exists is False. When deleted, head.exists is False.

Method GitToolkit.search_repo_code

Search code in the PR's repository via the GitHub Code Search API.

The repo:<owner>/<name> qualifier is automatically injected so the search is scoped to the PR's own repository only — it never exposes code from other repositories. Only the default branch is indexed by GitHub's Code Search.

Use this tool when you suspect a changed function has callers or related code in other files that are not shown in the PR diff. For example: searching for usages of a renamed function, finding all implementations of an interface, or locating a constant that was moved.

Note: the Code Search API is rate-limited separately from the REST API (30 requests/minute). When the quota is exceeded the tool returns SearchCodeResult(error='rate_limited', items=[]) without raising.

Example::

results = await toolkit.search_repo_code("class PRReviewResult")
for item in results.items:
    print(item["path"], item["html_url"])

search_repo_code(query: str, repository: Optional[str] = None, max_results: int = 20) -> 'SearchCodeResult'

Parameter Type Default Description
query str Code Search query (e.g. "def my_function" or "class MyModel language:python"). Do not include a repo: qualifier — it is added automatically.
repository Optional[str] None Repository in owner/name format. Uses the toolkit default when omitted.
max_results int 20 Maximum number of results to return (1-100, default 20).

Returns: 'SearchCodeResult' — class:SearchCodeResult with items containing raw GitHub Code Search item dicts (path, name, sha, html_url, score).

Method GitToolkit.get_contributor_stats

Return per-contributor weekly stats for the repository.

Calls GET /repos/{owner}/{repo}/stats/contributors. The endpoint is asynchronous on GitHub's side: the first call after a cold cache returns 202 with an empty body. This method retries with exponential backoff until it receives 200 (or gives up after max_retries), so callers always see a populated list.

get_contributor_stats(repository: Optional[str] = None) -> List[ContributorStats]

Parameter Type Default Description
repository Optional[str] None Target repository in owner/name format. Uses default when omitted.

Returns: List[ContributorStats] — List of :class:ContributorStats models with per-week breakdowns.

Method GitToolkit.get_weekly_commit_activity

Return the last 52 weeks of repo-wide commits broken down by day-of-week.

Calls GET /repos/{owner}/{repo}/stats/commit_activity. Handles the GitHub 202 async-compute pattern transparently.

get_weekly_commit_activity(repository: Optional[str] = None) -> List[Dict[str, Any]]

Parameter Type Default Description
repository Optional[str] None Target repository in owner/name format. Uses default when omitted.

Returns: List[Dict[str, Any]] — List of dicts, each with week (Unix epoch Sunday), total, and days (list of 7 day counts, Sun-Sat).

Method GitToolkit.get_code_frequency

Return per-week additions/deletions for the whole repository since inception.

Calls GET /repos/{owner}/{repo}/stats/code_frequency. Handles the GitHub 202 async-compute pattern transparently. Deletion counts are stored as non-negative integers (GitHub returns them as negative in the raw payload).

get_code_frequency(repository: Optional[str] = None) -> List[WeeklyCodeFrequency]

Parameter Type Default Description
repository Optional[str] None Target repository in owner/name format. Uses default when omitted.

Returns: List[WeeklyCodeFrequency] — List of :class:WeeklyCodeFrequency models, oldest first.

Class GitToolkitError

Raised when the toolkit cannot satisfy a request.

When the failure came from a GitHub API call the exception also carries the HTTP context, so callers can branch on :attr:status_code instead of sniffing the message, and can surface GitHub's own explanation to the operator. str(exc) is unchanged, which keeps older callers working.

Parameter Type Default Description
message str
status_code Optional[int] None
url Optional[str] None
api_message Optional[str] None
accepted_permissions Optional[str] None

Attributes:

Attribute Type Description
status_code HTTP status returned by GitHub, or None for failures raised before/without a request (e.g. unresolved repository).
url The API URL that failed.
api_message GitHub's own message field from the error body.
accepted_permissions The x-accepted-github-permissions response header, which names the fine-grained permission the endpoint wants (e.g. repository_hooks=write).

Class GitToolkitInput

Default configuration shared by all tools in the toolkit.

Fields:

Field Type Default Description
default_repository Optional[str] None Default GitHub repository in 'owner/name' format.
default_branch str 'main' Fallback branch used for pull requests.
github_token Optional[str] None Personal access token with repo scope for GitHub calls.
auth_type Literal['pat', 'github_app'] 'pat' Authentication backend. 'pat' uses github_token; 'github_app' uses app_id + installation_id + private key.
app_id Optional[int] None GitHub App ID (required when auth_type='github_app').
installation_id Optional[int] None Installation ID for the org/account the App is installed in (required when auth_type='github_app').
private_key Optional[str] None PEM contents of the App's private key. Mutually exclusive with private_key_path.
private_key_path Optional[str] None Filesystem path to the App's private key PEM. Mutually exclusive with private_key.
repositories Optional[Dict[str, RepositoryCredential]] None Named registry mapping an alias to that repository's credentials and defaults. All credentials are explicit-config only: the toolkit does NOT read GITHUB_* environment variables for auth (the default and ad-hoc connections also require explicitly passed credentials).

Class ListPullRequestsInput

Input payload for list_pull_requests.

Fields:

Field Type Default Description
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.
state Literal['open', 'closed', 'all'] 'open' Filter pull requests by state.
per_page int 100 Number of pull requests per page (max 100).

Class ListRepoDirectoryInput

Input for a ref-specific repository directory listing.

Fields:

Field Type Default Description
path str
ref str
repository Optional[str] None

Class RepoDirectoryEntry

One file or directory in a repository directory listing.

Fields:

Field Type Default Description
name str
path str
type Literal['file', 'dir']

Class RepoDirectoryListing

Directory listing at an explicitly selected repository ref.

Fields:

Field Type Default Description
exists bool
path str
ref str
repository str
entries List[RepoDirectoryEntry]

Class RepositoryCredential

Credentials + defaults for a single named repository in a registry.

Each entry in :attr:GitToolkit.repositories is one of these. The alias (the dict key) is how tools reference the repository by name; the repository field is the underlying owner/name slug used to build GitHub API URLs.

Fields:

Field Type Default Description
repository str GitHub repository in 'owner/name' format.
default_branch str 'main' Fallback branch used for pull requests against this repo.
auth_type Literal['pat', 'github_app'] 'pat' Authentication backend. 'pat' uses github_token; 'github_app' uses app_id + installation_id + private key.
github_token Optional[str] None Personal access token with repo scope (pat mode).
app_id Optional[int] None GitHub App ID (required when auth_type='github_app').
installation_id Optional[int] None Installation ID (required when auth_type='github_app').
private_key Optional[str] None PEM contents of the App's private key. Mutually exclusive with private_key_path.
private_key_path Optional[str] None Filesystem path to the App's private key PEM. Mutually exclusive with private_key.

Class SearchCodeResult

Return payload for search_repo_code.

Fields:

Field Type Default Description
repository str Repository in 'owner/name' format that was searched.
query str The original query string (without the auto-injected repo: qualifier).
total_count int Total number of matching results as reported by GitHub Code Search.
items List[Dict[str, Any]] Raw GitHub Code Search item list. Each item contains at minimum: 'path', 'name', 'sha', 'html_url', and 'score'.
error Optional[str] None Error indicator. 'rate_limited' when the search API quota is exhausted; None on success.

Class SearchRepoCodeInput

Input payload for search_repo_code.

Fields:

Field Type Default Description
query str Code Search query text without the 'repo:' qualifier — that qualifier is injected automatically to scope the search to the PR's repository.
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.
max_results int 20 Maximum number of results to return (1-100). GitHub caps this at 100 per request.

Class StatsNotReadyError

Raised when a /stats/* endpoint keeps answering 202.

GitHub computes repository statistics lazily: the first request for a cold repo returns 202 Accepted and only starts the computation, which can take minutes on a large repository. Exhausting the 202 retries therefore means "not ready yet", not "broken" — a distinct outcome callers should be able to defer on instead of treating as an error. It stays a :class:GitToolkitError so existing except GitToolkitError handlers keep working.

Parameter Type Default Description
message str
attempts Optional[int] None
url Optional[str] None

Attributes:

Attribute Type Description
attempts How many requests were made before giving up.

Class SubmitPRReviewInput

Input payload for submit_pr_review.

Fields:

Field Type Default Description
pr_number int Pull request number on the repository.
event Literal['APPROVE', 'REQUEST_CHANGES', 'COMMENT'] Review event to record on the pull request.
body str Review body in Markdown (required for REQUEST_CHANGES).
repository Optional[str] None Target repository: a registered alias from the toolkit's repositories registry, or a raw 'owner/name' slug. Uses the default repository when omitted.

Class WeeklyCodeFrequency

Repo-wide weekly additions/deletions totals.

Sourced from GET /repos/{owner}/{repo}/stats/code_frequency.

Fields:

Field Type Default Description
week_start datetime Sunday 00:00 UTC that begins this week.
additions int Total lines added across the repository in the week.
deletions int Total lines deleted (stored as non-negative; GitHub returns negative).

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally