GitHub Developer Course

Technology: github · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/github

Insight:

GitHub is where code lives, ships, and gets reviewed. This is a course, not just a reference: Git fundamentals → collaboration (PRs/reviews) → automation (Actions/CI) → security & supply chain → ecosystem → Claude Code. The two ideas that unlock everything: branches are cheap pointers to commits (so merge/rebase/squash are just different ways to reshape history), and a PR is a proposal gated by review + CI before it touches master. For codeAmani, a push to master is the deploy trigger, so rulesets + required CI keep production safe. Supply chain is now first-class: pin actions to SHAs (or adopt the actions.lock lockfile), attest what you ship, prefer GitHub Apps and fine-grained PATs over classic tokens, and verify every webhook's HMAC before parsing it. Agents (Copilot cloud agent, Claude via Agent HQ, and the Claude Code Action) all bill Actions minutes on private repos.

 ██████╗ ██╗████████╗██╗  ██╗██╗   ██╗██████╗
██╔════╝ ██║╚══██╔══╝██║  ██║██║   ██║██╔══██╗
██║  ███╗██║   ██║   ███████║██║   ██║██████╔╝
██║   ██║██║   ██║   ██╔══██║██║   ██║██╔══██╗
╚██████╔╝██║   ██║   ██║  ██║╚██████╔╝██████╔╝
 ╚═════╝ ╚═╝   ╚═╝   ╚═╝  ╚═╝ ╚═════╝ ╚═════╝

GitHub Developer Course

Focus: A hands-on path from git init to shipping with confidence: Git fundamentals, collaboration on GitHub, Actions/CI-CD, security and supply chain, the wider ecosystem, and driving it all from Claude Code. Grounded in docs.github.com, the GitHub changelog and the official release pages; reviewed 2026-10-20.

How this course works

Four levels, each ending with a ✅ capability checkpoint ("you can now…") and a 🛠 exercise. Work top-to-bottom the first time; use the command cheat-sheet and Table of Contents as reference after. The interactive learn module above this page (a branch & PR lifecycle simulator) is your illustration for Level 2; play with it before reading the merge/rebase section.

Table of Contents

Official Documentation

Resource URL
GitHub Docs (root) https://docs.github.com
GitHub Actions https://docs.github.com/en/actions
Secure use reference (Actions hardening) https://docs.github.com/en/actions/reference/security/secure-use
Artifact attestations https://docs.github.com/en/actions/concepts/security/artifact-attestations
Actions runner pricing https://docs.github.com/en/billing/reference/actions-runner-pricing
Code security https://docs.github.com/en/code-security
REST API + versions https://docs.github.com/en/rest/about-the-rest-api/api-versions
GraphQL API https://docs.github.com/en/graphql
Webhooks: validating deliveries https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries
gh CLI manual https://cli.github.com/manual
GitHub MCP server https://github.com/github/github-mcp-server
Claude Code Action https://github.com/anthropics/claude-code-action
GitHub changelog https://github.blog/changelog/

Verified versions (2026-10-20)

Thing Version Source
actions/checkout v7.0.1 (3d3c42e5aac5ba805825da76410c181273ba90b1) GitHub releases
actions/setup-node v7.1.0 (949feb2413d6458794dcd2491c4babbbce0c15c1) GitHub releases
actions/cache v6.1.0 GitHub releases
actions/upload-artifact / download-artifact v7.0.2 / v8.0.2 GitHub releases
actions/attest v4.2.2 (1e69f48acb82d1966a394da916b4c1698aa569d6); attest-build-provenance v4.2.2 is now a thin wrapper GitHub releases
actions/create-github-app-token v3.3.0 GitHub releases
actions/dependency-review-action v5.0.0 GitHub releases
github/codeql-action v4.39.0 (use @v4) GitHub tags
actions/upload-pages-artifact / deploy-pages v5.0.0 / v5.0.1 GitHub releases
anthropics/claude-code-action v1 → v1.0.254 (db77d4d3c98f3f6380e7cd45ffba2342a3dbde3c) GitHub tags
github/github-mcp-server v2.0.2 (2026-10-08) GitHub releases
gh CLI v2.102.0 cli/cli releases
@octokit/rest / octokit 22.0.1 / 5.0.5 (ESM-only, Node ≥ 20) npm view
@octokit/webhooks-methods / @octokit/webhooks 6.0.0 / 14.2.0 npm view
@anthropic-ai/claude-code 2.1.304 npm view
REST API version 2026-03-10 (newest); 2022-11-28 supported until 2028-03-10 docs.github.com

Level 1 — Git fundamentals

Git vs GitHub

Git is the version-control tool that runs on your machine. It records snapshots (commits) of your files. GitHub is the hosted home for Git repositories that adds collaboration: pull requests, reviews, issues, CI/CD, security, and agents.

   your machine (Git)                         GitHub (remote)
 ┌────────────────────┐    git push     ┌────────────────────┐
 │ working dir        │ ─────────────▶  │  origin/master     │
 │   └ staging (index)│                 │  PRs · Actions ·    │
 │       └ .git/ (commits, branches)    │  Issues · Security  │
 └────────────────────┘ ◀───────────── └────────────────────┘
                          git pull

A file moves through three states: working directory → staging area (git add) → committed history (git commit).

Setup & first-time config

# Install Git + the GitHub CLI
winget install Git.Git GitHub.cli     # Windows
brew install git gh                    # macOS
sudo apt install git gh               # Debian/Ubuntu (incl. WSL)

# One-time identity
git config --global user.name  "Your Name"
git config --global user.email "you@codeamani.com"
git config --global init.defaultBranch master   # codeAmani repos deploy from master
git config --global pull.rebase false            # merge on pull (or 'true' to rebase)

# Authenticate the CLI (browser flow; stores a token in the OS keychain)
gh auth login
gh --version   # expect 2.102.x or newer

The core loop

git init                      # start a repo here   (or: gh repo clone owner/name)
git status                    # what changed?
git add file.ts               # stage a change      (git add -A for everything)
git commit -m "feat: add login form"
git log --oneline --graph     # see history as a graph
git diff                      # unstaged changes    (git diff --staged for staged)

Write good commit messages: a short imperative summary (fix: handle null token), optionally a body explaining why. The codeAmani convention follows Conventional Commits (feat:, fix:, chore:, docs:).

Branches: the cheap pointer

A branch is just a movable pointer to a commit; creating one is instant and free. This is the mental model that makes everything else click.

git switch -c feature/mpesa-stk      # create + switch (old: git checkout -b)
git switch master                    # switch back
git branch                           # list local branches
git branch -d feature/mpesa-stk      # delete a merged branch

Remotes & pushing to GitHub

gh repo create codeAmani-Labs/my-app --private --source=. --push   # create + link + push
# …or link an existing remote
git remote add origin https://github.com/codeAmani-Labs/my-app.git
git push -u origin master            # -u sets the upstream once
git pull                             # fetch + merge remote changes
git fetch origin                     # download without merging
# .gitignore — never track secrets or build junk
.env*
!.env.example
node_modules/
.next/
*.log

✅ Checkpoint: You can initialise a repo, stage and commit changes, branch, and push to GitHub. 🛠 Exercise: Create a repo with gh repo create, add a README.md, commit on a feature/readme branch, and push it.


Level 2 — Collaboration

Merge vs rebase vs squash

The three ways to integrate a branch, and the concept developers most often get wrong. Play with the simulator above to see the commit graph redraw for each.

gitGraph
   commit id: "A"
   commit id: "B"
   branch feature
   checkout feature
   commit id: "D"
   commit id: "E"
   checkout main
   commit id: "C"
   merge feature
Strategy What it does History Use when
Merge Creates a merge commit joining both lines Preserves true branch shape Shared/long-lived branches; you want the full record
Rebase Replays your commits on top of the target Linear, no merge commits Cleaning up your local branch before a PR
Squash Combines all branch commits into one One tidy commit per feature Merging a PR into master (the codeAmani default)
git merge feature/x                  # merge feature/x into current branch
git rebase master                    # replay current branch on top of master
git rebase -i HEAD~3                  # interactively squash/reorder last 3 commits
# Golden rule: never rebase commits you've already pushed to a shared branch.

Pull requests: the unit of collaboration

A PR proposes merging one branch into another, gated by review + CI before it lands. Lifecycle: open → review → CI checks → approve → merge (or the merge queue on busy repos).

gh pr create --title "feat: Stripe checkout" --body "Adds Checkout Session + webhook"
gh pr create --fill                  # use branch name + last commit as title/body
gh pr list                           # open PRs
gh pr view 42 --web                  # open in browser
gh pr checks 42 --watch              # CI status for the PR, live
gh pr merge 42 --squash --delete-branch
gh pr merge 42 --squash --auto       # merge automatically once checks pass

Code review

gh pr diff 42                        # read the changes
gh pr review 42 --approve
gh pr review 42 --request-changes --body "Verify the Stripe signature before parsing"
gh pr review 42 --comment --body "Nice — one nit inline"

A good review checks correctness, security (no secrets, input validated, webhooks verified), tests, and clarity. Keep PRs small; they get reviewed faster and merge cleaner. AI reviewers (Copilot code review, the Claude Code Action) are a first pass, not a substitute for a human approval on master.

Resolving conflicts

git switch feature/x
git merge master                     # conflict markers appear in files
# Edit the <<<<<<< / ======= / >>>>>>> sections, choosing the right code, then:
git add resolved-file.ts
git commit                           # completes the merge

Undoing things safely

Goal Command Safe on shared history?
Discard unstaged file change git restore file ✅
Unstage a file git restore --staged file ✅
Amend the last commit git commit --amend ❌ (rewrites)
Undo a commit, keep changes git reset --soft HEAD~1 ❌
Revert a pushed commit git revert <sha> ✅ (new inverse commit)
Stash work-in-progress git stash / git stash pop ✅
Recover "lost" commits git reflog ✅ (your safety net)

git revert is the safe public undo; git reset/--amend rewrite history (force-push territory). When in doubt, git reflog remembers where everything was.

Issues, labels & Projects

gh issue create --title "Bug: webhook times out" --label bug,priority:high
gh issue list --assignee @me
gh issue close 17 --comment "Fixed in #42"
gh project list --owner codeAmani-Labs     # Projects (v2) boards

Rulesets & branch protection

Protect master so nothing merges unreviewed or red. Repository rulesets (Settings → Rules → Rulesets) are the current mechanism: they stack, can target many branches by pattern, can be set at org level, and support bypass lists. Classic branch protection still works.

# Classic branch protection via the REST API (still supported)
gh api -X PUT repos/codeAmani-Labs/my-app/branches/master/protection \
  --input - <<'JSON'
{
  "required_status_checks": { "strict": true, "contexts": ["lint", "typecheck", "test"] },
  "enforce_admins": true,
  "required_pull_request_reviews": { "required_approving_review_count": 1 },
  "restrictions": null
}
JSON
# Rulesets: list what's applied to a repo
gh api repos/codeAmani-Labs/my-app/rulesets

✅ Checkpoint: You can open a PR, review it, resolve conflicts, undo mistakes safely, and protect a branch. 🛠 Exercise: Open a PR from your feature/readme branch, request a change on it, push a fix, then squash-merge it with --auto.


Level 3 — Automation, security & ecosystem

GitHub Actions (CI/CD)

Workflows are YAML in .github/workflows/. Structure: events (on) → jobs → steps. Jobs run in parallel unless chained with needs.

flowchart LR
  PR["push / pull_request"] --> T["job: check<br/>matrix lint, typecheck, test"]
  T --> D["required checks green"]
  D --> V["squash-merge → Vercel auto-deploy"]
# .github/workflows/ci.yml — full file in github/examples/ci.yml
name: CI
on:
  push: { branches: [master] }
  pull_request: { branches: [master] }
  workflow_dispatch:           # manual "Run workflow" button

permissions:
  contents: read               # least privilege by default

concurrency:                   # cancel superseded runs of this workflow on the same ref
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  check:
    runs-on: ubuntu-latest
    timeout-minutes: 15        # default job cap is 6 h on GitHub-hosted runners
    strategy:
      fail-fast: false
      matrix:
        task: [lint, typecheck, test]
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with: { persist-credentials: false }
      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with: { node-version: "24", cache: npm }
      - run: npm ci
      - run: npm run ${{ matrix.task }}

Key building blocks:

gh workflow list
gh workflow run ci.yml --ref master
gh run watch                   # live-stream the active run
gh run view 12345678 --log-failed

Workflow security rules that bite:

Pinning actions: SHAs and the lockfile

A tag like @v7 is a movable pointer; if an action's repo is compromised the tag can be repointed. Two defences, strongest first:

  1. Workflow dependency lockfile (public preview). gh extension install github/gh-actions-lock, then run gh actions-lock at the repo root. It writes .github/workflows/actions.lock pinning every action (including transitive ones) to a commit and to the source repo's numeric owner/repo IDs, which Actions checks at run time. GitHub's docs say SHA pinning is no longer necessary in repos that adopt it. Dependabot regenerates lockfile entries when it bumps an onboarded workflow. Note: allowed-actions allowlists are then checked against the locked SHA, so tag-pinned allowlist entries stop matching.
  2. Full-length commit SHA in each uses: with the tag in a same-line comment: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1. Dependabot updates both the SHA and the comment.

Caveat: Dependabot alerts only fire for actions referenced by semver tag, not by SHA. Pinned repos rely on Dependabot version updates (package-ecosystem: github-actions) to stay patched.

OIDC: keyless cloud auth

With permissions: id-token: write, a job can mint a short-lived OIDC token (issuer https://token.actions.githubusercontent.com) and exchange it with a cloud provider (AWS, GCP, Azure, and now Anthropic's Workload Identity Federation) instead of storing a long-lived key. Scope the trust policy to repo:OWNER/REPO:ref:refs/heads/master or an environment, never just the org.

Artifact attestations & SLSA

Attestations are Sigstore-signed provenance claims (workflow, repo, commit SHA, trigger) that consumers check with gh attestation verify. Public repos sign with the Sigstore public-good instance (and a public transparency log); private repos use GitHub's own Sigstore instance.

permissions:
  contents: read
  id-token: write
  attestations: write
steps:
  # …build dist.tar.gz…
  - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
    with:
      subject-path: dist.tar.gz          # or subject-name + subject-digest for images
gh attestation verify dist.tar.gz -R codeAmani-Labs/my-app
gh attestation verify oci://ghcr.io/codeamani-labs/app:1.2.0 -R codeAmani-Labs/my-app
Setup SLSA level (per GitHub docs)
actions/attest in the build job Build L2
Build + attest inside a shared reusable workflow, verified with --signer-workflow Build L3
slsa-github-generator isolated builders Build L3 (codeAmani's documented default)

Only attest things people download and run (release tarballs, images, packages), not every test build. Full example: github/examples/release-attest.yml. Policy: see the Supply-Chain & Provenance section of CLAUDE.md and supply-chain/CLAUDE_CODE_INTEGRATION.md.

Actions pricing (2026)

Public repos on standard runners: free. Self-hosted runners: free (the announced $0.002/min self-hosted "cloud platform charge" for March 2026 was postponed in December 2025 and the billing docs still list self-hosted as free). Hosted-runner prices dropped by up to 39% on 2026-01-01. Private repos get a monthly quota, then pay per minute (rounded up per job):

Runner SKU $/min
Linux 1-core x64 actions_linux_slim 0.002
Linux 2-core x64 (ubuntu-latest) actions_linux 0.006
Linux 2-core arm64 actions_linux_arm 0.005
Windows 2-core x64 / arm64 actions_windows / _arm 0.010
macOS 3/4-core actions_macos 0.062
Linux 4 / 8 / 16-core (larger) linux_N_core 0.012 / 0.022 / 0.042
Plan Minutes / month Artifact + Packages storage Cache / repo
Free (user or org) 2,000 500 MB 10 GB
Pro 3,000 1 GB 10 GB
Team 3,000 2 GB 10 GB
Enterprise Cloud 50,000 50 GB 10 GB

Overage storage: $0.25/GB-month (artifacts + Packages), $0.07/GB-month (cache above 10 GB). Larger runners are never free and can't use included minutes. Agents bill minutes too: Copilot code review, Copilot cloud agent and third-party agents (Claude, Codex) consume Actions minutes on private repos (plus Copilot AI credits). Set a budget under Billing → Budgets and alerts. Arm Linux (ubuntu-24.04-arm) is the cheapest 2-core option for Node builds.

Security suite (shift left)

Feature Where it comes from Private repo needs
Dependency graph, Dependabot alerts + security updates + version updates All plans nothing extra
Secret scanning + push protection, AI-detected secrets, custom patterns, delegated bypass GitHub Secret Protection ($19 per active committer / month) Team or Enterprise plan
Code scanning (CodeQL), Copilot Autofix, dependency review, AI Scan, security campaigns GitHub Code Security ($30 per active committer / month) Team or Enterprise plan

Public repos get secret scanning, push protection and CodeQL code scanning free. Separately, push protection for users is on by default for every GitHub.com account and stops you pushing secrets to any public repo. Repository push protection is off by default; a repo admin or org owner enables it.

# .github/dependabot.yml (full file: github/examples/dependabot.yml)
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule: { interval: "weekly" }
    cooldown: { default-days: 5 }     # version updates default to a 3-day cooldown anyway
    groups:
      minor-and-patch: { update-types: ["minor", "patch"] }
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule: { interval: "weekly" }
# .github/workflows/codeql.yml — CodeQL code scanning (or use "default setup" in Settings)
name: CodeQL
on: { push: { branches: [master] }, pull_request: { branches: [master] } }
permissions: { contents: read }
jobs:
  analyze:
    runs-on: ubuntu-latest
    permissions: { security-events: write, contents: read }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: github/codeql-action/init@v4
        with: { languages: javascript-typescript }
      - uses: github/codeql-action/analyze@v4

Prefer code scanning default setup (Settings → Code security → CodeQL → Default) unless you need custom queries; it needs no workflow file. Add actions/dependency-review-action@v5 to PR CI to block PRs that introduce known-vulnerable dependencies (needs Code Security on private repos).

Tokens, PATs & GitHub Apps

Credential Use it for Notes
GITHUB_TOKEN (Actions) Anything inside a workflow on the same repo Auto-injected, expires with the job, scoped by permissions:
GitHub App installation token Bots, servers, cross-repo automation, webhooks 1-hour tokens, scoped to installed repos + declared permissions, not tied to a person. Preferred for anything long-lived
Fine-grained PAT Personal scripts, local MCP, CLI on one owner One owner per token, per-repo selection, expiry (default 30 days, max 366 or none if policy allows), org approval; max 50 per user
Classic PAT Only where fine-grained can't (Packages, Checks API, multi-org, outside-collaborator writes) Broad repo/workflow scopes across every repo you can access. Avoid
OIDC Keyless cloud/vendor auth from Actions No stored secret at all
# Mint an App token inside a workflow (client ID in a repo VARIABLE, key in a SECRET)
- uses: actions/create-github-app-token@v3
  id: app-token
  with:
    client-id: ${{ vars.APP_CLIENT_ID }}
    private-key: ${{ secrets.APP_PRIVATE_KEY }}
- run: gh issue list
  env:
    GH_TOKEN: ${{ steps.app-token.outputs.token }}

Server-side App auth with Octokit lives in github/examples/github-app.ts (new App({ appId, privateKey }) → app.getInstallationOctokit(id)).

Webhooks: verify, then parse

GitHub signs the raw body with your webhook secret (HMAC-SHA256) and sends X-Hub-Signature-256: sha256=<hex>. Verify with a constant-time compare before JSON.parse, respond 2xx within 10 seconds (queue heavy work), and dedupe on X-GitHub-Delivery (redeliveries reuse it). X-Hub-Signature (SHA-1) is legacy only.

// app/api/webhooks/github/route.ts (full file: github/examples/webhook-route.ts)
import { verify } from "@octokit/webhooks-methods";

export async function POST(req: Request): Promise<Response> {
  const secret = process.env.GITHUB_WEBHOOK_SECRET;
  const signature = req.headers.get("x-hub-signature-256");
  if (!secret || !signature) return new Response("unauthorized", { status: 401 });
  const rawBody = await req.text();
  if (!(await verify(secret, rawBody, signature))) {
    return new Response("bad signature", { status: 401 });
  }
  const event = req.headers.get("x-github-event");
  // …dedupe on x-github-delivery, enqueue, then:
  return new Response(event === "ping" ? "pong" : null, { status: event === "ping" ? 200 : 202 });
}

Test vector from the docs: secret It's a Secret to Everybody, payload Hello, World! → sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17.

REST, GraphQL & Octokit

# REST — anything the API exposes
gh api repos/codeAmani-Labs/my-app/pulls --jq '.[].title'
gh api -X POST repos/codeAmani-Labs/my-app/issues -f title="From the CLI" -f body="…"
gh api --paginate repos/codeAmani-Labs/my-app/issues --jq '.[].number'
# GraphQL — precise, fewer round-trips
gh api graphql -f query='query { viewer { login } }'
# Pin the REST API version for stable scripts
gh api -H "X-GitHub-Api-Version: 2026-03-10" repos/codeAmani-Labs/my-app

The REST API is date-versioned. 2026-03-10 is the newest version; requests without X-GitHub-Api-Version still default to 2022-11-28, which is supported until 2028-03-10 (each version gets at least 24 months after its successor ships; a retired version returns 410 Gone, and Deprecation/Sunset headers warn you first). gh api itself sends 2022-11-28 unless you pass -H (checked with gh api --verbose). Send the header explicitly and read the breaking-changes page before bumping. GraphQL is a single evolving schema; watch its changelog.

// Octokit (TypeScript) — full file: github/examples/octokit.ts
import { Octokit } from "@octokit/rest";          // @octokit/rest 22.0.1, ESM-only

const octokit = new Octokit({
  auth: process.env.GITHUB_TOKEN,
  userAgent: "codeamani-scripts/1.0",
  headers: { "X-GitHub-Api-Version": "2026-03-10" },
});

const prs = await octokit.paginate(octokit.rest.pulls.list, {
  owner: "codeAmani-Labs", repo: "my-app", state: "open", per_page: 100,
});

Pick the package: @octokit/rest for REST-only scripts; octokit (5.x) when you also need GraphQL, Apps (App), OAuth apps, webhooks, retries and throttling in one import. Both are ESM-only and need Node ≥ 20.

Packages & Releases

gh release create v1.2.0 --generate-notes     # notes from merged PRs
gh release list
# GitHub Packages (npm): "publishConfig": { "registry": "https://npm.pkg.github.com" }, then npm publish
# Packages storage shares the Actions artifact allowance (see pricing table)

Codespaces

A cloud dev environment defined by devcontainer.json, for instant, reproducible onboarding.

// .devcontainer/devcontainer.json
{
  "image": "mcr.microsoft.com/devcontainers/javascript-node:24",
  "features": { "ghcr.io/devcontainers/features/github-cli:1": {} },
  "postCreateCommand": "npm ci",
  "customizations": { "vscode": { "extensions": ["dbaeumer.vscode-eslint"] } }
}
gh codespace create -R codeAmani-Labs/my-app
gh codespace code            # open in VS Code

GitHub Pages

Free static hosting from a repo (docs/landing pages). Standard runners are free for Pages builds. Enable under Settings → Pages, or deploy via Actions:

permissions: { contents: read, pages: write, id-token: write }
# … build, then:
- uses: actions/upload-pages-artifact@v5
  with: { path: dist }
- uses: actions/deploy-pages@v5

✅ Checkpoint: You can write a pinned, least-privilege CI workflow; attest a release; enable Dependabot + CodeQL + push protection; choose between GITHUB_TOKEN, an App and a fine-grained PAT; and verify a webhook signature. 🛠 Exercise: Add examples/ci.yml to a repo, run gh actions-lock, enable Dependabot for github-actions, and wire examples/webhook-route.ts to a test webhook (use the docs' test vector first).


Level 4 — GitHub + AI agents

The GitHub MCP server

The official github/github-mcp-server (v2.0.2, Oct 2026) lets Claude read and act on repos, issues, PRs, Actions, and security alerts in-session. v2.0 added typed tool output schemas for clients on MCP spec 2026-07-28+.

Remote (hosted by GitHub, recommended). Endpoint https://api.githubcopilot.com/mcp/. Auth with OAuth (host-dependent) or a PAT in an Authorization: Bearer header. Read-only: append /readonly. Single toolset: https://api.githubcopilot.com/mcp/x/<toolset> (also /x/all). Or use headers: X-MCP-Toolsets, X-MCP-Tools, X-MCP-Readonly, X-MCP-Lockdown, X-MCP-Insiders.

# Claude Code ≥ 2.1.1 (per the server's install guide)
claude mcp add-json github '{"type":"http","url":"https://api.githubcopilot.com/mcp","headers":{"Authorization":"Bearer YOUR_FINE_GRAINED_PAT"}}' --scope user
# If add-json returns "Invalid input" on Windows, use the older form:
claude mcp add --transport http github https://api.githubcopilot.com/mcp -H "Authorization: Bearer YOUR_FINE_GRAINED_PAT"
claude mcp list
// .mcp.json (project scope) — read-only remote server, token from the environment
{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/readonly",
      "headers": { "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}" }
    }
  }
}

Local (Docker image or release binary). The local server now does a browser OAuth login on github.com by default (token kept in memory), or takes GITHUB_PERSONAL_ACCESS_TOKEN (takes precedence). Needed for GitHub Enterprise Server (GITHUB_HOST).

# OAuth login (publish the fixed callback port)
claude mcp add github -e GITHUB_OAUTH_CALLBACK_PORT=8085 -- \
  docker run -i --rm -p 127.0.0.1:8085:8085 -e GITHUB_OAUTH_CALLBACK_PORT ghcr.io/github/github-mcp-server
# PAT + explicit toolsets + read-only + lockdown
claude mcp add github -e GITHUB_PERSONAL_ACCESS_TOKEN -e GITHUB_TOOLSETS=default,actions,code_security -e GITHUB_READ_ONLY=1 -e GITHUB_LOCKDOWN_MODE=1 -- \
  docker run -i --rm -e GITHUB_PERSONAL_ACCESS_TOKEN -e GITHUB_TOOLSETS -e GITHUB_READ_ONLY -e GITHUB_LOCKDOWN_MODE ghcr.io/github/github-mcp-server
Toolset What it covers
context (default) Who am I / where am I. Strongly recommended
repos (default) Files, branches, commits, releases
issues (default) Create, comment, label, sub-issues
pull_requests (default) Create, review, merge, comment
users (default) User lookup
actions Workflows, runs, logs
code_security / secret_protection / dependabot Code-scanning, secret-scanning, Dependabot alerts
governance Rulesets and custom properties
copilot Assign work to Copilot cloud agent
others code_quality, discussions, gists, git, labels, notifications, orgs, projects, security_advisories, stargazers, copilot_issue_intents
remote-only copilot_spaces, github_support_docs_search

Lockdown mode filters content from public repos authored by people without push access, a best-effort guard against prompt injection via issues/PR comments. It is not an authorization boundary; the token's real permissions still apply. Turn it on for agents that read public issues.

The npm package @modelcontextprotocol/server-github is deprecated ("Package no longer supported"). Use the remote endpoint, the Docker image, or the release binary.

Claude Code GitHub Action

anthropics/claude-code-action@v1 runs Claude Code on your runner: mention @claude in an issue/PR, assign an issue, add a label, or run it with a prompt: on any event (scheduled audits, CI-failure fixes, PR review).

Full workflow: github/examples/claude.yml.

- uses: anthropics/claude-code-action@v1
  with:
    anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
    prompt: "Review this PR for security issues: secrets, unverified webhooks, missing input validation."
    claude_args: --max-turns 8

Copilot cloud agent & Claude on Agent HQ

Which to use? For codeAmani: the Claude Code Action when you want Claude with your own API key, your own CLAUDE.md, plugins and tool allowlist. Claude on Agent HQ when a teammate already has Copilot and wants to hand off an issue from the GitHub UI. Either way, the output is a PR that goes through the same review + required checks.

Claude Code automations

<!-- .claude/commands/review-pr.md -->
Review pull request #$ARGUMENTS.
1. Use the GitHub MCP to fetch the PR diff, description and existing comments.
2. Check for bugs, security issues (secrets, unverified webhooks, unvalidated input), missing tests, and convention drift.
3. Post a review: approve if safe, else request changes with specific line notes.

Usage: /review-pr 42

// scripts/auto-pr.mjs — open a PR after a feature branch is pushed (Stop hook)
import { execFileSync } from "node:child_process";   // execFileSync + arg arrays = no shell injection
const branch = execFileSync("git", ["branch", "--show-current"]).toString().trim();
if (branch === "main" || branch === "master") process.exit(0);
if (execFileSync("git", ["status", "--porcelain"]).toString()) process.exit(0);
try { execFileSync("gh", ["pr", "create", "--fill"], { stdio: "inherit" }); } catch { /* PR may already exist */ }

✅ Checkpoint: You can give Claude scoped, read-only GitHub access via MCP, run Claude in Actions without a stored key, and hand an issue to an agent knowing what it costs. 🛠 Exercise: Add examples/claude.yml to a sandbox repo, comment @claude explain the CI workflow on an issue, and check the run's minutes in the Actions usage view.


Environment variables

Real secrets (store them in the secrets vault / Vercel env / Actions secrets; placeholders only):

GITHUB_TOKEN=github_pat_...
GITHUB_WEBHOOK_SECRET=replace_with_random_32_byte_hex...
GITHUB_APP_PRIVATE_KEY=pem_contents_with_newlines_escaped_as_backslash_n...
ANTHROPIC_API_KEY=sk-ant-...

Non-secret settings (plain config or Actions variables, not secrets):

Name Example Used by
GITHUB_APP_ID / APP_CLIENT_ID 123456 / Iv23li... Octokit App, create-github-app-token
GITHUB_APP_INSTALLATION_ID 98765432 getInstallationOctokit()
GITHUB_TOOLSETS default,actions,code_security local MCP server
GITHUB_READ_ONLY / GITHUB_LOCKDOWN_MODE 1 local MCP server
GITHUB_HOST https://ghe.example.com MCP / gh against GHES or ghe.com
ANTHROPIC_FEDERATION_RULE_ID / ANTHROPIC_ORGANIZATION_ID fdrl_... / UUID Claude Code Action WIF

gh reads GH_TOKEN (or GITHUB_TOKEN) from the environment; inside Actions pass GH_TOKEN: ${{ github.token }} via env:.

Command cheat-sheet

# Daily loop
git status / git add -A / git commit -m "…" / git push
git switch -c feature/x      # branch        git switch master
git pull --rebase            # update cleanly  git stash / git stash pop
# History
git log --oneline --graph --all
git revert <sha>             # safe undo of a pushed commit
git reflog                   # find lost commits
# GitHub via gh
gh pr create --fill / gh pr checks 42 --watch / gh pr merge 42 --squash --auto
gh issue create / gh run watch / gh run view --log-failed
gh release create vX --generate-notes
gh attestation verify dist.tar.gz -R OWNER/REPO
gh extension install github/gh-actions-lock && gh actions-lock
gh api repos/OWNER/REPO/... # raw REST/GraphQL

More: github/reference/gh-cli-cheatsheet.md.

Troubleshooting

Issue Fix
gh: command not found Install via winget/brew/apt; gh --version should be 2.102+
401 on MCP HTTP Token expired or missing permission; regenerate the fine-grained PAT with the repos + permissions the toolsets need
claude mcp add-json → "Invalid input" (Windows) Use claude mcp add --transport http github <url> -H "Authorization: Bearer …"
Push rejected (non-fast-forward) git pull --rebase then push
Push blocked by push protection A secret was detected: remove it, rotate it, recommit (bypass only for confirmed false positives)
Webhook signature never matches Verify the raw body (no JSON re-serialise), use X-Hub-Signature-256, check the secret is set on the hook; a proxy may be rewriting the body
Webhook shows "timed out" Respond 2xx within 10 s; enqueue the work
Workflow didn't run Check on: triggers + branch/path filters; workflows from forks need approval
Run fails after gh actions-lock An allowlist entry is tag-pinned; switch it to a wildcard or full SHA
410 Gone from REST You pinned a retired API version; move to 2026-03-10
Unexpected Actions bill Agents and Copilot code review consume minutes on private repos; add timeout-minutes, concurrency, and a budget
Accidentally committed a secret Rotate it immediately; then history rewrite (git filter-repo) + force-push

codeAmani notes

Official docs: