Skip to main content

Easy to use Python SDK for the GitCode REST API. Providing builtin CLI tool, and optional LLM integration (MCP and OpenAI tool) for agents. Community-maintained.

Project description

GitCode-API

PyPI - Version PyPI Downloads CodeFactor GitHub Badge GitCode Badge

Docs 中文README

gitcode-api is a community-maintained Python SDK for the GitCode REST API. It provides easy-to-use synchronous and asynchronous clients, repository-scoped helpers, and lightweight response models so you can work with GitCode from Python without hand-writing raw HTTP requests. The gitcode_api.llm module adds an OpenAI-style function tool and MCP service so agents can reuse the same resource-oriented API.

Why This Project

  • Community project for developers who want a practical GitCode Python library.
  • Sync and async clients with a consistent API surface.
  • Resource groups such as client.repos, client.pulls, and client.users.
  • Repository defaults via owner= and repo= on the client.
  • Sphinx docs plus a mirrored GitCode REST API reference in docs/.

Installation

Install from PyPI:

pip install -U gitcode-api

Authentication

Pass api_key= directly, or set GITCODE_ACCESS_TOKEN in your environment:

export GITCODE_ACCESS_TOKEN="your-token"

If your token is stored in encrypted form, pass decrypt= to decode either an encrypted api_key= value or an encrypted GITCODE_ACCESS_TOKEN value before the client uses it.

from gitcode_api import GitCode
from trusted_library import decrypt_token

client = GitCode(
    api_key="encrypted-token",
    decrypt=decrypt_token,
)

CLI

After installation, you can invoke the SDK directly from the command line:

gitcode-api repos get --api-key "$GITCODE_ACCESS_TOKEN" --owner SushiNinja --repo GitCode-API
python -m gitcode_api pulls list --api-key "$GITCODE_ACCESS_TOKEN" --owner SushiNinja --repo GitCode-API --state open

With gitcode-api[mcp] installed (Python 3.10+), you can start the bundled FastMCP server over stdio:

gitcode-api serve --api-key "$GITCODE_ACCESS_TOKEN"

Use gitcode-api serve -h for defaults such as --owner, --repo, and --transport.

Commands mirror the synchronous resource methods on GitCode, using the pattern gitcode-api <resource> <method> .... For methods that accept extra **params or **payload, pass repeated --set key=value flags or --set-json '{"key": "value"}'.

Quick Start

Sync client

from gitcode_api import GitCode

client = GitCode(
    owner="SushiNinja",
    repo="GitCode-API",
)

repo = client.repos.get()
branches = client.branches.list(per_page=5)

print(repo.full_name)
for branch in branches:
    print(branch.name)

Async client

import asyncio
from gitcode_api import AsyncGitCode

async def main() -> None:
    client = AsyncGitCode(owner="SushiNinja", repo="GitCode-API")
    pulls = await client.pulls.list(state="open", per_page=20)
    print(len(pulls))

asyncio.run(main())

Context managers

GitCode and AsyncGitCode (and the lower-level SyncAPIClient / AsyncAPIClient) support with / async with. Leaving the block calls close() / await close() on the underlying client automatically, including a custom http_client= you passed in. close() also clears the LRU cache used by each resource group's method_signature(...) helper (see the Available Resources section).

from gitcode_api import GitCode

with GitCode(owner="SushiNinja", repo="GitCode-API") as client:
    repo = client.repos.get()
    print(repo.full_name)
import asyncio
from gitcode_api import AsyncGitCode

async def main() -> None:
    async with AsyncGitCode(owner="SushiNinja", repo="GitCode-API") as client:
        pulls = await client.pulls.list(state="open", per_page=20)
        print(len(pulls))

asyncio.run(main())

Common Workflows

Create a pull request:

from gitcode_api import GitCode

client = GitCode(owner="SushiNinja", repo="GitCode-API")

pull = client.pulls.create(
    title="Add feature",
    head="feature-branch",
    base="main",
    body="Implements the new flow.",
)
print(pull.number)

Get the authenticated user:

from gitcode_api import GitCode

client = GitCode()

user = client.users.me()
print(user.login)

Search repositories:

from gitcode_api import GitCode

client = GitCode()

repos = client.search.repositories(q="sdk language:python", per_page=10)
for repo in repos:
    print(repo.full_name)

Available Resources

Both GitCode and AsyncGitCode expose:

  • repos and contents
  • branches and commits
  • issues and pulls
  • labels, milestones, and members
  • releases, tags, and webhooks
  • users, orgs, search, and oauth

Every resource group inherits a cached methods property from the shared resource base: a tuple of public callable names in stable SDK order (underscore-segment sort key, not plain A–Z on the full identifier). Private names and the introspection helpers methods and method_signature are omitted. For example, client.pulls.methods helps with discovery or tooling without reading the full manual list. For one method’s parameters and return type, call client.pulls.method_signature("list_issues") (a cached string from inspect.signature, with gitcode_api._models. stripped from annotations).

LLM tools and MCP

The gitcode_api.llm module exposes a single logical tool, gitcode_api_tool, that routes calls to sync or async SDK resources. Model-facing parameters match the JSON schema used by OpenAI-style function tools:

Parameter Role
op_type Required. Resource group on the client (same names as GitCode attributes: repos, pulls, issues, and so on).
action Method on that resource (for example get, list). Empty with help returns method discovery text.
params Keyword arguments for the method as a JSON object; omitted or null is treated as {}.
help When true, returns formatted help (available methods or a target signature) instead of performing a normal API call where applicable.

Successful results are JSON-friendly (APIObject.to_dict(), base64-wrapped bytes, and similar). Failures are returned as objects with "error": true and a "message" string (HTTP and configuration errors include extra fields when available).

OpenAI tool (GitCodeOpenAITool)

No extra dependencies beyond the core package. Build a Chat Completions–style tool definition with .tool or .to_dict(), then invoke the same instance with the arguments above (sync) or configure async mode for await.

from gitcode_api.llm import GitCodeOpenAITool

tool = GitCodeOpenAITool(owner="SushiNinja", repo="GitCode-API")
tools_payload = [tool.tool]  # or tool.to_dict() for a single entry

# Sync invocation (default)
result = tool("repos", "get", params={})

# Async client / awaitable wrapper
async_tool = GitCodeOpenAITool(owner="SushiNinja", repo="GitCode-API", async_mode=True)
# await async_tool("pulls", "list", params={"state": "open", "per_page": 5})

You can pass the emitted tool definition into chat.completions.create(...) and handle tool calls directly:

import json
from openai import OpenAI
from gitcode_api.llm import GitCodeOpenAITool

tools = {
    "gitcode_api_tool": GitCodeOpenAITool(owner="SushiNinja", repo="GitCode-API"),
}
client = OpenAI(
    api_key="your-openai-compatible-api-key",
    base_url="https://your-openai-compatible-base-url/v1",
)

response = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{"role": "user", "content": "List the last 5 commits."}],
    tools=[tools["gitcode_api_tool"].tool],
)

for tool_call in response.choices[0].message.tool_calls:
    selected_tool = tools[tool_call.function.name]
    print(f"Calling tool {tool_call.function.name}({tool_call.function.arguments}):")
    print("---result---")
    print(selected_tool(**json.loads(tool_call.function.arguments)))
    print("---result---")

Constructor options mirror GitCode / AsyncGitCode: client=, async_client=, api_key=, owner=, repo=, base_url=, timeout=, and decrypt=. For dict-driven setups that reserve the name async, you may pass **{"async": True} instead of async_mode=True (but not both).

MCP server and MCP tool (FastMCP)

MCP integration uses FastMCP. Install the optional extra (requires Python 3.10+ because of the fastmcp dependency):

pip install 'gitcode-api[mcp]'
  • create_mcp_server — builds a FastMCP instance with gitcode_api_tool already registered; optional name=, tool=, and extra keyword arguments are forwarded to FastMCP(...).
  • GitCodeMCP — thin wrapper that constructs that server and registers the tool; unknown attributes are delegated to the underlying FastMCP object (for example transport helpers exposed by your FastMCP version).
  • create_mcp_gitcode_api_tool — returns the standalone async callable used as the tool body (for custom wiring).
  • register_mcp_gitcode_api_tool — attaches that callable to an existing FastMCP-compatible object (mcp.tool(...) or mcp.add_tool(...)).
from gitcode_api.llm import create_mcp_server

mcp = create_mcp_server(name="GitCode API", owner="SushiNinja", repo="GitCode-API")
# Run or export the server using FastMCP’s API for your version (stdio, HTTP, etc.).

The same server is available from the CLI as gitcode-api serve (see the CLI section).

To share auth or clients across tools, build GitCodeLLMTool once (from gitcode_api.llm._tool import GitCodeLLMTool) and pass it as tool= into GitCodeMCP, create_mcp_server, register_mcp_gitcode_api_tool, or create_mcp_gitcode_api_tool.

Examples

Runnable examples live in examples/:

  • get_current_user.py
  • get_repository_overview.py
  • list_pull_requests.py
  • async_list_branches.py

Example scripts load shared configuration from examples/.env using python-dotenv.

uv run python examples/get_current_user.py
uv run python examples/get_repository_overview.py
uv run python examples/list_pull_requests.py
uv run python examples/async_list_branches.py

See examples/.env.example for the expected variables.

Documentation

  • Project docs entry: docs/index.rst
  • SDK docs: docs/sdk/index.rst
  • REST API mirror: docs/rest_api/index.rst

Build the docs locally from the repository root. The docs Makefile target removes stale docs/_build and docs/sdk/generated output, then runs Sphinx (via uv) with the html, epub, and singlehtml builders. Outputs land under docs/_build/html/, docs/_build/epub/ (including GitCodeAPI.epub), and docs/_build/singlehtml/:

make docs

Other common targets from the repository root (after uv sync --all-groups so optional dependency groups are available):

  • make docs-clean — remove docs/_build and docs/sdk/generated without rebuilding.
  • make format — Ruff lint fixes, import sorting, and formatting.
  • make test — install the package into the active environment and run pytest.
  • make docstring — pydocstyle checks for gitcode_api/.
  • make binary — PyInstaller one-file CLI under dist/ (requires the binary group).

FAQ

SSL or corporate network errors ("self-signed certificate")

If GitCode HTTPS fails behind a corporate proxy or private PKI, point httpx at a CA bundle with verify (similar in spirit to REQUESTS_CA_BUNDLE for requests):

from gitcode_api import GitCode
from httpx import Client

with GitCode(
    owner="SushiNinja",
    repo="GitCode-API",
    http_client=Client(verify="path/to/my/certificate.crt"),
) as client:
    repo = client.repos.get()
    pulls = client.pulls.list(state="open", per_page=5)

Use httpx.AsyncClient(verify=...) with AsyncGitCode for async code.

The OpenAI tool (GitCodeOpenAITool) and MCP helpers accept the same client= / async_client= arguments (or a shared GitCodeLLMTool via tool= with those clients set). Build GitCode / AsyncGitCode with your custom http_client once and pass it through so LLM tool calls reuse the same TLS settings.

Project Status

This is a community project and is still evolving. API coverage is already broad, but some endpoints and behaviors may continue to be refined as the SDK grows.

Contributing

Issues, bug reports, API coverage improvements, docs fixes, and pull requests are welcome. If you are using GitCode heavily and notice missing endpoints or awkward ergonomics, contributions are especially appreciated.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gitcode_api-1.2.6.tar.gz (76.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

gitcode_api-1.2.6-py3-none-any.whl (71.9 kB view details)

Uploaded Python 3

File details

Details for the file gitcode_api-1.2.6.tar.gz.

File metadata

  • Download URL: gitcode_api-1.2.6.tar.gz
  • Upload date:
  • Size: 76.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for gitcode_api-1.2.6.tar.gz
Algorithm Hash digest
SHA256 9b3ef3f85456030d13f0834a0ca8915c4d74a9b77f5f016b8dddfccec43f6408
MD5 4fc1e3a2ca0acf26b4a8866c27e3834e
BLAKE2b-256 e44fdd095c9f6cd7fc1d7f908f5b3154d60e23ebf0a3bace8b8400116d14c24c

See more details on using hashes here.

Provenance

The following attestation bundles were made for gitcode_api-1.2.6.tar.gz:

Publisher: python-publish.yml on Trenza1ore/GitCode-API

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file gitcode_api-1.2.6-py3-none-any.whl.

File metadata

  • Download URL: gitcode_api-1.2.6-py3-none-any.whl
  • Upload date:
  • Size: 71.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for gitcode_api-1.2.6-py3-none-any.whl
Algorithm Hash digest
SHA256 f62bd40822f26cc8a0987c77ef4f32e75a7fed6b28978c352ffee8e2b4bc7ed6
MD5 e3a88e9f9c485e638b7406fe187e1a77
BLAKE2b-256 25616be8f5f8172de3dd67e45cde1d3c23fdb50e3244f8e72cd1dd8151802786

See more details on using hashes here.

Provenance

The following attestation bundles were made for gitcode_api-1.2.6-py3-none-any.whl:

Publisher: python-publish.yml on Trenza1ore/GitCode-API

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page