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
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, andclient.users. - Repository defaults via
owner=andrepo=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:
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:
reposandcontentsbranchesandcommitsissuesandpullslabels,milestones, andmembersreleases,tags, andwebhooksusers,orgs,search, andoauth
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. |
Tool payloads are JSON-serialized strings: successes look like plain objects (APIObject.to_dict(), base64-wrapped bytes, and similar); failures use "error": true, a "message" string, and optional extra fields on HTTP/configuration errors.
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. Each invocation applies json.dumps to payload so the return type is always str. The default keyword argument indent=2 pretty-prints JSON; pass indent=None for a compact single-line string.
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
import os
from typing import Dict, List
from openai import OpenAI
from gitcode_api.llm import GitCodeOpenAITool
MESSAGE_SEP = "\n" + "=" * 60 + "\n"
USER_QUERY = "List the repos owned by SushiNinja."
CONVERSATION: List[Dict[str, str]] = [dict(role="user", content=USER_QUERY)]
tools = {"gitcode_api_tool": GitCodeOpenAITool()}
client = OpenAI()
print("U:\n" + USER_QUERY + MESSAGE_SEP)
while True:
response = (
client.chat.completions.create(
model="gpt-5.4-nano",
messages=CONVERSATION,
tools=[tools["gitcode_api_tool"].tool],
)
.choices[0]
.message
)
CONVERSATION.append(response.to_dict())
print("A:\n" + (response.content or ""))
for tool_call in response.tool_calls or []:
selected_tool = tools[tool_call.function.name]
result = selected_tool(**json.loads(tool_call.function.arguments))
CONVERSATION.append(dict(role="tool", tool_call_id=tool_call.id, content=result))
print(f"<Calling tool {tool_call.function.name}({tool_call.function.arguments})>")
print(MESSAGE_SEP)
if not response.tool_calls:
break
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 aFastMCPinstance withgitcode_api_toolalready registered; optionalname=,tool=, and extra keyword arguments are forwarded toFastMCP(...).GitCodeMCP— thin wrapper that constructs that server and registers the tool; unknown attributes are delegated to the underlyingFastMCPobject (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(...)ormcp.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.pyget_repository_overview.pylist_pull_requests.pyasync_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— removedocs/_buildanddocs/sdk/generatedwithout 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 forgitcode_api/.make binary— PyInstaller one-file CLI underdist/(requires thebinarygroup).
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gitcode_api-1.2.10.tar.gz.
File metadata
- Download URL: gitcode_api-1.2.10.tar.gz
- Upload date:
- Size: 83.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d4f14f53ea56876bcc28e178772e44205f37a3460a8da93625da419b39ab0416
|
|
| MD5 |
8251fdcf74b571505f4a750ec52d2b73
|
|
| BLAKE2b-256 |
4e33b7f7bb6f7d9ee0ad9749ed3b6510a7ba234d93aeb33dfe2f6dece77480f5
|
Provenance
The following attestation bundles were made for gitcode_api-1.2.10.tar.gz:
Publisher:
python-publish.yml on Trenza1ore/GitCode-API
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
gitcode_api-1.2.10.tar.gz -
Subject digest:
d4f14f53ea56876bcc28e178772e44205f37a3460a8da93625da419b39ab0416 - Sigstore transparency entry: 1461116361
- Sigstore integration time:
-
Permalink:
Trenza1ore/GitCode-API@fd331cca30a6c496f5518722771c478989e9d41f -
Branch / Tag:
refs/tags/1.2.10 - Owner: https://github.com/Trenza1ore
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@fd331cca30a6c496f5518722771c478989e9d41f -
Trigger Event:
release
-
Statement type:
File details
Details for the file gitcode_api-1.2.10-py3-none-any.whl.
File metadata
- Download URL: gitcode_api-1.2.10-py3-none-any.whl
- Upload date:
- Size: 76.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
775117eac06b626339329d4a94f753bf011dedeb19a8df653a8d574eff368427
|
|
| MD5 |
486dade65c8308792572461ac4a86c8c
|
|
| BLAKE2b-256 |
42a7201bd5c540f9f6d85c8458f6af60356aeb35461f9e9e2b7cddc88739c355
|
Provenance
The following attestation bundles were made for gitcode_api-1.2.10-py3-none-any.whl:
Publisher:
python-publish.yml on Trenza1ore/GitCode-API
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
gitcode_api-1.2.10-py3-none-any.whl -
Subject digest:
775117eac06b626339329d4a94f753bf011dedeb19a8df653a8d574eff368427 - Sigstore transparency entry: 1461116475
- Sigstore integration time:
-
Permalink:
Trenza1ore/GitCode-API@fd331cca30a6c496f5518722771c478989e9d41f -
Branch / Tag:
refs/tags/1.2.10 - Owner: https://github.com/Trenza1ore
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@fd331cca30a6c496f5518722771c478989e9d41f -
Trigger Event:
release
-
Statement type: