Skip to main content

Easy to use Python SDK for the GitCode REST API. Providing builtin CLI tool, and optional LLM integration (MCP, OpenAI tool, and openJiuwen 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, an MCP service, and an openJiuwen tool integration 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, and openJiuwen tool for LLM agent usage.
  • Provide MCP service that directly installs to your IDE of choice, such as Cursor and VS Code!
  • Provides an mcpb bundle you can install directly in the Claude desktop app; download it from Release.

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 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, MCP, and openJiuwen

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.

openJiuwen (LocalFunction)

openJiuwen is an open agent platform. With the separate openjiuwen package installed (Python 3.11+), create_openjiuwen_gitcode_api_tool returns an openJiuwen LocalFunction that uses the same op_type / action / params / help arguments as the OpenAI adapter. Invocation is async-only (await jiuwen_tool.invoke({...})).

pip install openjiuwen
from gitcode_api.llm import create_openjiuwen_gitcode_api_tool

jiuwen_tool = create_openjiuwen_gitcode_api_tool(owner="SushiNinja", repo="GitCode-API")
# jiuwen_tool.card — name, description, input_params
# await jiuwen_tool.invoke({"op_type": "repos", "action": "get", "params": {}})

Optional name= and description= override the default tool card. Constructor options otherwise mirror GitCode / AsyncGitCode (client=, async_client=, api_key=, owner=, repo=, base_url=, timeout=, decrypt=).

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), MCP helpers, and create_openjiuwen_gitcode_api_tool accept the same client= / async_client= arguments (OpenAI and MCP also accept a shared GitCodeLLMTool via tool=). 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.9.tar.gz (83.6 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.9-py3-none-any.whl (76.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: gitcode_api-1.2.9.tar.gz
  • Upload date:
  • Size: 83.6 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.9.tar.gz
Algorithm Hash digest
SHA256 1ee677f0d1419b5de1f64ee2812f223c385bef9ff927876278dbae29443dfde2
MD5 0312d8e673464db2252d4f0b129a2044
BLAKE2b-256 875c277d336699013f28579d321e073632b3fe75729732b5415da2b3ada439ab

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: gitcode_api-1.2.9-py3-none-any.whl
  • Upload date:
  • Size: 76.5 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.9-py3-none-any.whl
Algorithm Hash digest
SHA256 285e7c007b1b4100f036c4f92a38d5cefada9fe8da6ef746305409ce356d6e6f
MD5 c0a8d44a93d76e6d9e3722f6cebc6498
BLAKE2b-256 99332fa119071e4d93f0b541ccb55af9d9be973203ac58a2168f4c7e9559582a

See more details on using hashes here.

Provenance

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