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 Install in Cursor Install in VS Code 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/.
  • Provides MCP server & OpenAI tool for LLM agent usage.
  • Provide MCP service that directly installs to your IDE of choice, such as Cursor and VS Code!

Installation

Install from PyPI:

pip install -U gitcode-api

Install the MCP server to your AI-powered IDE of choice: Install in Cursor Install in VS Code Install in VS Code Insiders Install in Visual Studio Install in Goose Add MCP Server GitCode API to LM Studio

For detailed setup (including installing to services like Claude Code / Codex): see install_mcp_server.md.

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.

Claude Desktop (MCPB): published GitHub Releases include a gitcode-<version>.mcpb bundle for one-click installation as a Claude Desktop extension; see Anthropic’s guide, Build a desktop extension with MCPB. From a checkout you can run make mcpb (requires the @anthropic-ai/mcpb CLI on your PATH).

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.8.tar.gz (82.0 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.8-py3-none-any.whl (74.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: gitcode_api-1.2.8.tar.gz
  • Upload date:
  • Size: 82.0 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.8.tar.gz
Algorithm Hash digest
SHA256 bfd68b545c3974423696c55fb6f4bf790c368c1522deaaee7be76e6e6e9153f3
MD5 6911f7cb3d9c4fd89e8269013b77e9c4
BLAKE2b-256 538169587226083178f5a38a18d0e5a54fd782c2f4d5d3e1f54e63125ffa2100

See more details on using hashes here.

Provenance

The following attestation bundles were made for gitcode_api-1.2.8.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.8-py3-none-any.whl.

File metadata

  • Download URL: gitcode_api-1.2.8-py3-none-any.whl
  • Upload date:
  • Size: 74.8 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.8-py3-none-any.whl
Algorithm Hash digest
SHA256 a535619cefc2a2e6232c389fbee6df0c87986041657e7c0faf815ad541f3cb58
MD5 c037839e9e3bc9de35b01a91a2e65384
BLAKE2b-256 5f23862e07c3d41637593654b207832d712442b5b9171a058362bc82f5c57191

See more details on using hashes here.

Provenance

The following attestation bundles were made for gitcode_api-1.2.8-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