#!/usr/bin/env node
/* Copyright (C) 2026 Moko Enterprises <hello@mokoenterprises.us>
 *
 * This file is part of a Moko Enterprises project.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 * FILE INFORMATION
 * DEFGROUP: git-api-mcp.Server
 * INGROUP: git-api-mcp
 * REPO: https://git.mokoenterprises.us/MokoEnterprises/git-api-mcp
 * PATH: /source/index.ts
 * VERSION: 01.00.00
 * BRIEF: MCP server entry point - registers all Git API tools
 */

import * as https from 'node:https';
import * as http from 'node:http';
import { createRequire } from 'node:module';
import { McpServer, type ToolCallback } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { ZodRawShapeCompat } from '@modelcontextprotocol/sdk/server/zod-compat.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import { loadConfig, getConnection } from './config.js';
import { GitClient } from './client.js';
import { formatApiError } from './api-error.js';
import type { GitConfig, ApiResponse } from './types.js';
import {
	setGeneratedConfig,
	setGeneratedServer,
	setRegisteredNames,
} from './generated-runtime.js';
import { registerGeneratedToolsV2 } from './tools.generated.js';
import { resolveGuardConfig, runGuardedMerge } from './rapid-merge-guard.js';
import { leafSlug, qualifyWikiTitle } from './wiki-path.js';
import {
	normalizeRef,
	strictRefsEnabled,
	formatAmbiguityMessage,
	probeRefCollision,
	type RefClient,
	type RefCollision,
} from './ref-guard.js';
import { probeBackends, warnBackendStatus, runMokoCli, cliRunEnabled, assertSafeArgs } from './mokocli.js';
import {
	investigatePremergeCi,
	evaluatePremergeGate,
	renderPremergeReport,
	renderMergeStatus,
	fetchMergeStatus,
	mergeBlockedReason,
	translateMergeFailure,
	type PremergePolicy,
	type PremergeReport,
	type MergeStatus,
} from './premerge-ci.js';

let config: GitConfig;

function clientFor(connection?: string): GitClient {
	return new GitClient(getConnection(config, connection));
}

// Client targeting the MokoGIT-custom API surface (/api/v2). Use ONLY for the
// custom endpoints that were forked from v1 to v2: repo /metadata, /platforms,
// org /branch_protections (repo-level branch_protections stays v1), and the
// org issue taxonomy (/issue-statuses, /issue-priorities, /issue-types).
// All standard Gitea endpoints must keep using clientFor (/api/v1).
function clientV2For(connection?: string): GitClient {
	return new GitClient(getConnection(config, connection), 'v2');
}

// Encode a single URL path segment (owner, repo, ref, name, numeric id, …),
// matching the generated tools' encodeURIComponent(String(x)) convention.
function enc(segment: string | number): string {
	return encodeURIComponent(String(segment));
}

// (normalizeRef now lives in ./ref-guard — shared by the read guard and the
//  mutating-tool fail-closed check. See that module for the #339 rationale.)

// Encode a multi-segment file path while PRESERVING the '/' separators: a file
// `path` param legitimately contains slashes, so each segment is encoded
// individually and rejoined. Leading/trailing slashes are kept. This also
// neutralizes any '..' traversal in the encoded form ('..' → '..' stays literal
// per-segment and never collapses the path once sent to the API).
function encPath(path: string): string {
	return path.split('/').map((s) => encodeURIComponent(s)).join('/');
}

// Binary (octet-stream) POST that honors the connection's `insecure` TLS flag,
// mirroring GitClient.request(). Used by the attachment-upload tools, which send
// a raw Buffer body and so cannot route through GitClient's JSON methods. The
// caller MUST pass a fully-encoded path (use enc()/encPath() on every segment).
function uploadBinary(
	conn: { baseUrl: string; token: string; insecure?: boolean },
	encodedPath: string,
	query: Record<string, string>,
	buf: Buffer,
): Promise<ApiResponse> {
	const baseUrl = conn.baseUrl.replace(/\/+$/, '') + '/api/v1';
	const url = new URL(`${baseUrl}${encodedPath}`);
	for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
	const is_https = url.protocol === 'https:';
	const transport = is_https ? https : http;
	return new Promise((resolve, reject) => {
		const options: https.RequestOptions = {
			hostname: url.hostname,
			port: url.port || (is_https ? 443 : 80),
			path: url.pathname + url.search,
			method: 'POST',
			headers: {
				'Authorization': `token ${conn.token}`,
				'Content-Type': 'application/octet-stream',
				'Content-Length': String(buf.byteLength),
			},
			timeout: 30_000,
		};
		if (conn.insecure && is_https) options.rejectUnauthorized = false;
		const req = transport.request(options, (res) => {
			const chunks: Buffer[] = [];
			res.on('data', (c: Buffer) => chunks.push(c));
			res.on('end', () => {
				const raw = Buffer.concat(chunks).toString('utf-8');
				let data: unknown;
				try { data = JSON.parse(raw); } catch { data = raw; }
				resolve({ status: res.statusCode ?? 0, data });
			});
		});
		req.on('error', (err) => reject(err));
		req.on('timeout', () => { req.destroy(); reject(new Error('Request timed out')); });
		req.write(buf);
		req.end();
	});
}

function formatResponse(res: ApiResponse, warning?: string | null): { content: Array<{ type: 'text'; text: string }> } {
	if (res.status >= 400) {
		// mokogit-mcp #311: emit an actionable multi-line error block (status +
		// Gitea payload + invalid-parameter hints) via the shared formatter.
		const body = formatApiError(res);
		const text = warning ? `${warning}\n\n${body}` : body;
		return { content: [{ type: 'text' as const, text }] };
	}
	const body = JSON.stringify(res.data, null, 2);
	const text = warning ? `${warning}\n\n${body}` : body;
	return { content: [{ type: 'text' as const, text }] };
}

// Build a one-line caller-facing error response (matches the inline style the
// issue write tools use for non-HTTP validation errors like missing/ambiguous
// metadata).
function errorContent(message: string): { content: Array<{ type: 'text'; text: string }> } {
	return { content: [{ type: 'text' as const, text: `Error: ${message}` }] };
}

// ── Issue metadata name→ID resolution (mokogit-mcp #285) ──────────────────
//
// MokoGIT's issue taxonomy (status / priority / type) is a set of ORG-level
// definitions, each with an opaque numeric id and a human name. Callers think
// in names ("Bug", "High", "Resolved"), so the issue write tools accept either
// the numeric *_id or a *_name. A name is resolved here against the org's live
// definitions — the repo owner IS the org, matching git_issue_set_status's
// existing closes_issue lookup. Resolution is a unique, case-insensitive name
// match; an unknown or ambiguous name errors with the list of available names
// rather than guessing an id.
const ISSUE_META_ENDPOINT = {
	status: 'issue-statuses',
	priority: 'issue-priorities',
	type: 'issue-types',
} as const;
type IssueMetaKind = keyof typeof ISSUE_META_ENDPOINT;

async function resolveIssueMetaId(
	connection: string | undefined,
	org: string,
	kind: IssueMetaKind,
	name: string,
): Promise<{ id: number } | { error: string }> {
	const res = await clientV2For(connection).get(`/orgs/${enc(org)}/${ISSUE_META_ENDPOINT[kind]}`);
	if (res.status >= 400 || !Array.isArray(res.data)) {
		const msg = (res.data as { message?: string })?.message ?? `HTTP ${res.status}`;
		return { error: `Could not list ${kind} definitions for org "${org}" to resolve ${kind}_name "${name}": ${msg}` };
	}
	const defs = res.data as Array<{ id?: number; name?: string }>;
	const want = name.trim().toLowerCase();
	const matches = defs.filter((d) => String(d.name ?? '').trim().toLowerCase() === want);
	const available = defs.map((d) => d.name).filter(Boolean).join(', ') || '(none)';
	if (matches.length === 1 && typeof matches[0].id === 'number') return { id: matches[0].id };
	if (matches.length === 0) return { error: `No ${kind} named "${name}" in org "${org}". Available ${kind} names: ${available}.` };
	return { error: `Ambiguous ${kind} name "${name}" in org "${org}" (${matches.length} definitions share it) — pass the numeric ${kind}_id instead. Available ${kind} names: ${available}.` };
}

// Resolve any of the three *_name inputs to their numeric *_id for the issue
// write tools. Rejects passing BOTH an id and a name for the same family.
// Returns only the families that were supplied (id or name); omitted families
// stay absent so callers can distinguish "not set" from "cleared" (id 0).
async function resolveIssueMeta(
	connection: string | undefined,
	org: string,
	input: {
		status_id?: number; status_name?: string;
		priority_id?: number; priority_name?: string;
		type_id?: number; type_name?: string;
	},
): Promise<{ status_id?: number; priority_id?: number; type_id?: number } | { error: string }> {
	const out: { status_id?: number; priority_id?: number; type_id?: number } = {};
	for (const kind of ['status', 'priority', 'type'] as const) {
		const id = input[`${kind}_id`];
		const name = input[`${kind}_name`];
		if (id !== undefined && name !== undefined) {
			return { error: `Pass either ${kind}_id or ${kind}_name, not both.` };
		}
		if (name !== undefined) {
			const r = await resolveIssueMetaId(connection, org, kind, name);
			if ('error' in r) return r;
			out[`${kind}_id`] = r.id;
		} else if (id !== undefined) {
			out[`${kind}_id`] = id;
		}
	}
	return out;
}

// ── Channel-name ref collision guardrail (mokogit-mcp #236) ───────────────
//
// MokoGIT's release model uses channel-named ROLLING tags (`stable`, `dev`,
// `rc`, `beta`, `alpha`) that are force-advanced to each build. On the
// channel-named-branch repos this means a git tag AND a branch can share the
// same name at DIFFERENT commits. Git's bare-ref precedence resolves the name
// to the TAG before the branch, so a tool handed a bare channel name silently
// addresses the tag with no signal that a same-named branch exists and differs.
//
// #237 folded a non-fatal WARNING into read responses. This UPGRADES it to
// ENFORCEMENT (strict mode, ON by default; disable with MOKOGIT_MCP_STRICT_REFS=0):
//   • Read tools: a bare ambiguous ref now returns a structured ERROR (naming
//     both targets + how to qualify) INSTEAD of the possibly-wrong object.
//   • Mutating tools: FAIL CLOSED on a bare ambiguous ref before the write.
// When strict is OFF the guard degrades to the #237 warning behaviour.
//
// The pure decision logic (qualified/SHA detection, strict flag, message, exact
// ref SHA) lives in ./ref-guard so it is unit-testable; clientFor() GitClients
// satisfy that module's RefClient transport interface.

// Probe one or more ref names for a channel-name tag/branch collision. Returns
// the first ambiguous collision found (names are probed in parallel), or null.
async function firstRefCollision(
	client: RefClient,
	owner: string,
	repo: string,
	refNames: Array<string | undefined>,
): Promise<Extract<RefCollision, { kind: 'ambiguous' }> | null> {
	const results = await Promise.all(
		refNames.map((n) => probeRefCollision(client, owner, repo, n)),
	);
	for (const r of results) {
		if (r.kind === 'ambiguous') return r;
	}
	return null;
}

// Fail-closed guard for MUTATING tools. In strict mode, if any supplied ref name
// is a bare ambiguous channel name, return a structured error response and DO
// NOT perform the write; otherwise return null (proceed). In non-strict mode a
// collision never blocks (callers that want the warning use the read path).
// Fail-open on any probe error: a guard hiccup never blocks a legitimate write.
async function assertRefsUnambiguous(
	client: RefClient,
	owner: string,
	repo: string,
	refNames: Array<string | undefined>,
): Promise<{ content: Array<{ type: 'text'; text: string }> } | null> {
	if (!strictRefsEnabled()) return null;
	const collision = await firstRefCollision(client, owner, repo, refNames);
	if (!collision) return null;
	return errorContent(
		`Refused — ambiguous ref (strict mode). ${formatAmbiguityMessage(collision)}\n` +
		`  Set MOKOGIT_MCP_STRICT_REFS=0 to disable enforcement.`,
	);
}

// ── Inline file content for contents-ext / file-contents (mokogit-mcp #336) ──
//
// Gitea's contents-ext and file-contents endpoints return a file entry's
// metadata (sha, size, encoding) but leave `content: null` — the bytes are not
// inlined — so every "read a file" otherwise becomes two round-trips (meta →
// GET /git/blobs/<sha>). This post-processor walks the parsed response and, for
// each regular FILE entry that carries a blob `sha` but a null `content`, best-
// effort fetches the blob and populates `content` (base64) + `encoding` inline
// so one call returns the bytes. It is:
//   • size-capped  — files larger than INLINE_CONTENT_MAX_BYTES are left as-is
//     (content stays null) to avoid huge payloads; a note is attached;
//   • fail-open    — any blob-fetch error leaves that entry untouched and never
//     fails the whole call (the metadata response is preserved);
//   • shape-preserving — only the `content`/`encoding` (and a `_content_note`)
//     fields of file entries are touched; every other field/entry is verbatim.
// Deferred from #342 as an N+1; implemented here with the cap + fail-open guard.
const INLINE_CONTENT_MAX_BYTES = 512 * 1024; // 512 KiB per file

// Collect every file entry in a contents-ext / file-contents response that is a
// candidate for inlining (type==='file', content==null, string sha). The shape
// varies: a single file object, an array of entries (file-contents / a dir), or
// a contents-ext wrapper ({ file_contents, dir_contents, ... }); nulls (missing
// files in a batch) are skipped. Mutating the returned object refs mutates data.
function collectInlineTargets(data: unknown): Array<Record<string, unknown>> {
	const out: Array<Record<string, unknown>> = [];
	const visit = (v: unknown): void => {
		if (Array.isArray(v)) { for (const el of v) visit(el); return; }
		if (!v || typeof v !== 'object') return;
		const o = v as Record<string, unknown>;
		if (o['type'] === 'file' && (o['content'] === null || o['content'] === undefined)
			&& typeof o['sha'] === 'string') {
			out.push(o);
		}
		// Recurse into contents-ext wrapper fields that can hold nested entries.
		for (const key of ['file_contents', 'dir_contents', 'entries', 'contents']) {
			if (key in o) visit(o[key]);
		}
	};
	visit(data);
	return out;
}

// Best-effort inline the bytes for every null-content file entry in `data`.
// Mutates `data` in place. Never throws.
async function inlineFileContents(client: GitClient, owner: string, repo: string, data: unknown): Promise<void> {
	let targets: Array<Record<string, unknown>>;
	try { targets = collectInlineTargets(data); } catch { return; }
	await Promise.all(targets.map(async (entry) => {
		const sha = entry['sha'] as string;
		const size = typeof entry['size'] === 'number' ? (entry['size'] as number) : undefined;
		if (size !== undefined && size > INLINE_CONTENT_MAX_BYTES) {
			entry['_content_note'] = `content not inlined: ${size} bytes exceeds ${INLINE_CONTENT_MAX_BYTES}-byte cap; fetch GET /git/blobs/${sha}`;
			return;
		}
		try {
			const blob = await client.get(`/repos/${enc(owner)}/${enc(repo)}/git/blobs/${enc(sha)}`);
			if (blob.status >= 400 || !blob.data || typeof blob.data !== 'object') return;
			const b = blob.data as Record<string, unknown>;
			if (typeof b['content'] === 'string') {
				entry['content'] = b['content'];
				entry['encoding'] = typeof b['encoding'] === 'string' ? b['encoding'] : 'base64';
			}
		} catch {
			// fail-open: leave content null on any fetch error
		}
	}));
}

// Run a GET and, in parallel, probe the given ref name(s) for a channel-name
// tag/branch collision. STRICT (default): a bare ambiguous ref returns a
// structured ERROR instead of the (possibly wrong) object. NON-STRICT: fold a
// non-fatal warning into the response (the #237 behaviour). Fail-open on probe
// errors so the real call is never broken. When `inlineContents` is set,
// best-effort inline null `content` file bytes (mokogit-mcp #336) before
// formatting.
async function getWithRefGuard(
	connection: string | undefined,
	owner: string,
	repo: string,
	refNames: Array<string | undefined>,
	endpoint: string,
	params?: Record<string, string>,
	inlineContents = false,
): Promise<{ content: Array<{ type: 'text'; text: string }> }> {
	const client = clientFor(connection);
	// mokogit-mcp #339: the contents/raw family's `ref` QUERY param wants a
	// BARE name; a full-ref form (refs/heads/<b>) 400s/404s. Normalize both the
	// query param and the collision-probe names so a copy-pasted full ref works.
	if (params && typeof params['ref'] === 'string') {
		const nref = normalizeRef(params['ref']);
		if (nref !== undefined) params['ref'] = nref;
	}
	const strict = strictRefsEnabled();
	const [res, collision] = await Promise.all([
		client.get(endpoint, params),
		firstRefCollision(client, owner, repo, refNames),
	]);
	const response = res as ApiResponse;
	if (collision) {
		if (strict) {
			// Fail before returning the object git's bare-name precedence resolved
			// to (the tag) — the caller must qualify the ref.
			return errorContent(
				`Ambiguous ref — read refused (strict mode). ${formatAmbiguityMessage(collision)}\n` +
				`  Set MOKOGIT_MCP_STRICT_REFS=0 to fall back to a non-fatal warning.`,
			);
		}
		// mokogit-mcp #336: inline null file bytes before formatting the warned response.
		if (inlineContents && response.status < 400) {
			await inlineFileContents(client, owner, repo, response.data);
		}
		return formatResponse(response, `⚠ ${formatAmbiguityMessage(collision)}`);
	}
	if (inlineContents && response.status < 400) {
		await inlineFileContents(client, owner, repo, response.data);
	}
	return formatResponse(response);
}

// Shared suffix appended to ref/branch/sha param descriptions on ref-resolving
// READ tools (mokogit-mcp #236). Strict mode (ON by default) REFUSES a bare
// channel name that is both a branch and a tag at different commits — qualify
// with refs/heads/<name> or refs/tags/<name>; toggle with MOKOGIT_MCP_STRICT_REFS=0.
const STRICT_REF_NOTE =
	' STRICT REFS (#236): a bare channel name (stable/dev/rc/…) that resolves to BOTH a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> or refs/tags/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).';

const ConnectionParam = {
	connection: z.string().optional().describe('Named connection from config (uses default if omitted)'),
};

const PaginationParams = {
	page: z.number().optional().describe('Page number (1-based)'),
	limit: z.number().optional().describe('Items per page (max 50)'),
};

function pageQuery(params: { page?: number; limit?: number }): Record<string, string> {
	const q: Record<string, string> = {};
	if (params.page !== undefined) q['page'] = String(params.page);
	if (params.limit !== undefined) q['limit'] = String(params.limit);
	return q;
}

const OwnerRepo = {
	owner: z.string().describe('Repository owner (user or org)'),
	repo: z.string().describe('Repository name'),
};

// Resolve the real package version from package.json (single source of truth,
// kept in sync with the Makefile PROJECT_VERSION) rather than a hardcoded string.
const pkg = createRequire(import.meta.url)('../package.json') as { version?: string };
const SERVER_VERSION = pkg.version ?? '0.0.0';

const server = new McpServer({
	name: 'mokogit-mcp',
	version: SERVER_VERSION,
});

// ── Tool registration wrapper (Git → MokoGIT brand normalization) ────
//
// Canonical tool names are `mokogit_*`. For a transition window the older
// `mokogit_*` names and the original `git_*` names are ALSO registered as
// deprecated aliases so existing agent configs / skills keep working. Legacy
// aliases can be disabled by setting MOKOGIT_MCP_LEGACY_ALIASES (or the older
// MOKOGIT_MCP_LEGACY_ALIASES) to a falsy value (0/false/off/no); they are
// enabled by default. Disabling them exposes only the canonical name per tool.
const LEGACY_ALIASES: boolean = (() => {
	const v = process.env.MOKOGIT_MCP_LEGACY_ALIASES ?? process.env.MOKOGIT_MCP_LEGACY_ALIASES;
	if (v === undefined) return true;
	return !/^(0|false|off|no)$/i.test(v.trim());
})();

// registerTool(name, description, schema, handler) - mirrors the typed
// server.tool(name, description, paramsSchema, cb) overload so call sites keep
// full zod-schema → handler-arg inference. Call sites pass the historical
// `git_*` name; this registers the canonical `mokogit_*` tool and, when
// aliases are enabled, the deprecated `mokogit_*` and `git_*` names pointing
// at the same handler.
// Every tool name registered on the server (canonical bases + deprecated
// aliases). Shared with generated-runtime so the auto-generated v2 tools skip
// any name already owned by a hand-written registration — the hand-written
// tools (esp. the guardrail wrappers: deduped git_issue_create, the
// ref-collision wrapper, the cascade-required git_pull_merge/git_pull_create)
// always win and are never overwritten.
const registeredNames = new Set<string>();

function registerTool<Args extends ZodRawShapeCompat>(
	name: string,
	description: string,
	paramsSchema: Args,
	cb: ToolCallback<Args>,
): void {
	const isGit = name.startsWith('git_');
	const base = isGit ? name.slice('git_'.length) : name;
	// Canonical is the bare base (e.g. `issue_get`) — the MCP server is already
	// named `mokogit`, so the full id reads `mcp__mokogit__issue_get` instead of
	// the redundant `mcp__mokogit__mokogit_issue_get` doubling.
	const canonical = base;
	server.tool(canonical, description, paramsSchema, cb);
	registeredNames.add(canonical);
	if (LEGACY_ALIASES && isGit) {
		server.tool('mokogit_' + base, description, paramsSchema, cb); // deprecated (brand-prefixed)
		registeredNames.add('mokogit_' + base);
		server.tool(name, description, paramsSchema, cb); // deprecated (git_*)
		registeredNames.add(name);
	}
}

// ── User / Auth ─────────────────────────────────────────────────────────

registerTool(
	'git_me',
	'Get the authenticated user info',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/user')),
);

// ── Operation backends: mokogit-cli (MokoCLI) — precedence api > mokogit-cli > git ──
//
// The REST API is the PRIMARY path: every other tool here calls it directly, and
// that is what you should use for anything the API covers. The mokogit-cli binary
// is a FALLBACK backend for CLI-only operations (or when the API is unavailable);
// plain git is the last resort. These two tools expose that layer.

registerTool(
	'cli_status',
	'Report the MokoGIT MCP operation backends and their precedence (api > mokogit-cli > git): which are available, the resolved mokogit-cli/git binary paths and versions, and the active backend. The REST API is always primary; mokogit-cli and git are fallbacks. Use this to check whether CLI-assisted operations are available on this host.',
	{},
	async () => {
		const status = await probeBackends();
		return { content: [{ type: 'text' as const, text: JSON.stringify(status, null, 2) }] };
	},
);

registerTool(
	'cli_run',
	'Run a mokogit-cli (MokoCLI) subcommand as a FALLBACK backend and return its exit code, stdout and stderr. DISABLED by default — an operator must opt in with $MOKOGIT_ENABLE_CLI_RUN=1 (arbitrary CLI execution). Precedence is api > mokogit-cli > git — prefer the REST API tools for anything they cover; use this only for CLI-only operations or when the API is unavailable. Arguments are passed as argv (no shell); option-like args (leading "-") are rejected unless allowlisted or $MOKOGIT_CLI_ALLOW_FLAGS=1; any cwd must be inside $MOKOGIT_CLI_WORKDIR. Refuses with a clear message when disabled or when mokogit-cli is not installed (check cli_status).',
	{
		args: z.array(z.string()).describe('mokogit-cli arguments as an argv array, e.g. ["version"] or ["repo","list"]. Passed directly to the binary (no shell).'),
		cwd: z.string().optional().describe('Working directory — must resolve inside $MOKOGIT_CLI_WORKDIR (optional).'),
		timeout_seconds: z.number().int().positive().max(600).optional().describe('Max run time in seconds (default 60).'),
		input: z.string().optional().describe('Optional data to write to the CLI’s stdin.'),
	},
	async ({ args, cwd, timeout_seconds, input }) => {
		if (!cliRunEnabled()) {
			return { content: [{ type: 'text' as const, text: 'cli_run is disabled. Arbitrary mokogit-cli execution is an operator opt-in — set $MOKOGIT_ENABLE_CLI_RUN=1 to enable it. The REST API tools are the primary path (precedence api > mokogit-cli > git); use cli_status to see backend availability.' }] };
		}
		try {
			assertSafeArgs(args);
			const r = await runMokoCli(args, {
				cwd,
				timeoutMs: timeout_seconds ? timeout_seconds * 1000 : undefined,
				input,
			});
			const text = [
				`$ ${r.command}`,
				`exit: ${r.code}${r.ok ? '' : ' (non-zero)'}`,
				r.stdout ? `\n--- stdout ---\n${r.stdout.trimEnd()}` : '',
				r.stderr ? `\n--- stderr ---\n${r.stderr.trimEnd()}` : '',
			].filter(Boolean).join('\n');
			return { content: [{ type: 'text' as const, text }] };
		} catch (err) {
			return { content: [{ type: 'text' as const, text: err instanceof Error ? err.message : String(err) }] };
		}
	},
);

registerTool(
	'git_user_orgs',
	'List organizations the authenticated user belongs to',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/orgs', pageQuery({ page, limit }))),
);

registerTool(
	'git_user_repos',
	'List repositories owned by the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/repos', pageQuery({ page, limit }))),
);

// ── Repository CRUD ─────────────────────────────────────────────────────

registerTool(
	'git_repo_get',
	'Get repository details',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}`)),
);

registerTool(
	'git_repo_create',
	'Create a new repository',
	{
		name: z.string().describe('Repository name'),
		org: z.string().optional().describe('Organization (omit for personal)'),
		description: z.string().optional().describe('Description'),
		private: z.boolean().optional().describe('Private repository'),
		auto_init: z.boolean().optional().describe('Initialize with README'),
		default_branch: z.string().optional().describe('Default branch (default "main")'),
		template: z.boolean().optional().describe('Mark as template repository'),
		...ConnectionParam,
	},
	async ({ name, org, description, private: priv, auto_init, default_branch, template: tmpl, connection }) => {
		const client = clientFor(connection);
		const body: Record<string, unknown> = { name };
		if (description) body.description = description;
		if (priv !== undefined) body.private = priv;
		if (auto_init !== undefined) body.auto_init = auto_init;
		if (default_branch) body.default_branch = default_branch;
		if (tmpl !== undefined) body.template = tmpl;
		const endpoint = org ? `/orgs/${enc(org)}/repos` : '/user/repos';
		return formatResponse(await client.post(endpoint, body));
	},
);

registerTool(
	'git_repo_delete',
	'Delete a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}`)),
);

registerTool(
	'git_repo_edit',
	'Edit repository settings',
	{
		...OwnerRepo,
		description: z.string().optional().describe('New description'),
		private: z.boolean().optional().describe('Set private/public'),
		has_issues: z.boolean().optional().describe('Enable issues'),
		has_wiki: z.boolean().optional().describe('Enable wiki'),
		has_pull_requests: z.boolean().optional().describe('Enable PRs'),
		default_branch: z.string().optional().describe('Default branch'),
		archived: z.boolean().optional().describe('Archive/unarchive'),
		...ConnectionParam,
	},
	async ({ owner, repo, description, private: priv, has_issues, has_wiki, has_pull_requests, default_branch, archived, connection }) => {
		const body: Record<string, unknown> = {};
		if (description !== undefined) body.description = description;
		if (priv !== undefined) body.private = priv;
		if (has_issues !== undefined) body.has_issues = has_issues;
		if (has_wiki !== undefined) body.has_wiki = has_wiki;
		if (has_pull_requests !== undefined) body.has_pull_requests = has_pull_requests;
		if (default_branch !== undefined) body.default_branch = default_branch;
		if (archived !== undefined) body.archived = archived;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}`, body));
	},
);

registerTool(
	'git_repo_fork',
	'Fork a repository',
	{
		...OwnerRepo,
		organization: z.string().optional().describe('Fork to this org (omit for personal)'),
		name: z.string().optional().describe('Custom name for fork'),
		...ConnectionParam,
	},
	async ({ owner, repo, organization, name, connection }) => {
		const body: Record<string, unknown> = {};
		if (organization) body.organization = organization;
		if (name) body.name = name;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/forks`, body));
	},
);

registerTool(
	'git_repo_generate',
	'Create a new repository from a template repository',
	{
		template_owner: z.string().describe('Owner of the template repository'),
		template_repo: z.string().describe('Name of the template repository'),
		owner: z.string().describe('Target owner (user or org) for the new repo'),
		name: z.string().describe('Name for the new repository'),
		description: z.string().optional().describe('Description for the new repo'),
		private: z.boolean().optional().describe('Make the new repo private'),
		git_content: z.boolean().optional().describe('Copy git content (commits, branches) from template (default true)'),
		topics: z.boolean().optional().describe('Copy topics from template'),
		git_hooks: z.boolean().optional().describe('Copy git hooks from template'),
		webhooks: z.boolean().optional().describe('Copy webhooks from template'),
		labels: z.boolean().optional().describe('Copy labels from template'),
		default_branch: z.string().optional().describe('Default branch for new repo'),
		...ConnectionParam,
	},
	async ({ template_owner, template_repo, owner, name, description, private: priv, git_content, topics, git_hooks, webhooks, labels, default_branch, connection }) => {
		const body: Record<string, unknown> = { owner, name };
		if (description) body.description = description;
		if (priv !== undefined) body.private = priv;
		if (git_content !== undefined) body.git_content = git_content;
		if (topics !== undefined) body.topics = topics;
		if (git_hooks !== undefined) body.git_hooks = git_hooks;
		if (webhooks !== undefined) body.webhooks = webhooks;
		if (labels !== undefined) body.labels = labels;
		if (default_branch) body.default_branch = default_branch;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(template_owner)}/${enc(template_repo)}/generate`, body));
	},
);

registerTool(
	'git_repo_search',
	'Search repositories',
	{
		q: z.string().describe('Search query'),
		topic: z.boolean().optional().describe('Search in topics'),
		sort: z.enum(['alpha', 'created', 'updated', 'size', 'stars', 'forks']).optional().describe('Sort field'),
		order: z.enum(['asc', 'desc']).optional().describe('Sort order'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ q, topic, sort, order, page, limit, connection }) => {
		const params: Record<string, string> = { q, ...pageQuery({ page, limit }) };
		if (topic !== undefined) params['topic'] = String(topic);
		if (sort) params['sort'] = sort;
		if (order) params['order'] = order;
		return formatResponse(await clientFor(connection).get('/repos/search', params));
	},
);

registerTool(
	'git_org_repos',
	'List repositories in an organization',
	{
		org: z.string().describe('Organization name'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/repos`, pageQuery({ page, limit }))),
);

// ── File Contents ───────────────────────────────────────────────────────

registerTool(
	'git_file_get',
	'Get file contents from a repository',
	{
		...OwnerRepo,
		filepath: z.string().describe('File path (e.g. "src/index.ts")'),
		ref: z.string().optional().describe('Branch/tag/commit (default: default branch).' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, filepath, ref, connection }) => {
		const params: Record<string, string> = {};
		if (ref) params['ref'] = ref;
		return getWithRefGuard(connection, owner, repo, [ref], `/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(filepath)}`, params);
	},
);

registerTool(
	'git_dir_get',
	'Get directory contents (file listing) from a repository',
	{
		...OwnerRepo,
		dirpath: z.string().optional().describe('Directory path (default: root)'),
		ref: z.string().optional().describe('Branch/tag/commit.' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, dirpath, ref, connection }) => {
		const path = dirpath ? `/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(dirpath)}` : `/repos/${enc(owner)}/${enc(repo)}/contents`;
		const params: Record<string, string> = {};
		if (ref) params['ref'] = ref;
		return getWithRefGuard(connection, owner, repo, [ref], path, params);
	},
);

registerTool(
	'git_file_create_or_update',
	'Create or update a file in a repository',
	{
		...OwnerRepo,
		filepath: z.string().describe('File path'),
		content: z.string().describe('File content (will be base64-encoded automatically)'),
		message: z.string().describe('Commit message'),
		branch: z.string().optional().describe('Branch (default: default branch). STRICT REFS (#236): a bare channel name that is both a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		sha: z.string().optional().describe('SHA of existing file (required for updates)'),
		...ConnectionParam,
	},
	async ({ owner, repo, filepath, content, message, branch, sha, connection }) => {
		const client = clientFor(connection);
		const blocked = await assertRefsUnambiguous(client, owner, repo, [branch]);
		if (blocked) return blocked;
		const body: Record<string, unknown> = {
			content: Buffer.from(content).toString('base64'),
			message,
		};
		if (branch) body.branch = normalizeRef(branch);
		if (sha) body.sha = sha;
		return formatResponse(await client.put(`/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(filepath)}`, body));
	},
);

registerTool(
	'git_file_delete',
	'Delete a file from a repository',
	{
		...OwnerRepo,
		filepath: z.string().describe('File path to delete'),
		sha: z.string().describe('SHA of file to delete'),
		message: z.string().describe('Commit message'),
		branch: z.string().optional().describe('Branch. STRICT REFS (#236): a bare channel name that is both a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		...ConnectionParam,
	},
	async ({ owner, repo, filepath, sha, message, branch, connection }) => {
		const client = clientFor(connection);
		const blocked = await assertRefsUnambiguous(client, owner, repo, [branch]);
		if (blocked) return blocked;
		const body: Record<string, unknown> = { sha, message };
		if (branch) body.branch = normalizeRef(branch);
		return formatResponse(await client.delete(`/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(filepath)}`, body));
	},
);

registerTool(
	'git_tree_get',
	'Get the git tree for a repository (recursive file listing)',
	{
		...OwnerRepo,
		sha: z.string().describe('Tree SHA or branch name.' + STRICT_REF_NOTE),
		recursive: z.boolean().optional().describe('Recursive listing (default true)'),
		...ConnectionParam,
	},
	async ({ owner, repo, sha, recursive, connection }) => {
		const params: Record<string, string> = {};
		if (recursive !== false) params['recursive'] = 'true';
		return getWithRefGuard(connection, owner, repo, [sha], `/repos/${enc(owner)}/${enc(repo)}/git/trees/${enc(sha)}`, params);
	},
);

// ── Branches ────────────────────────────────────────────────────────────

registerTool(
	'git_branches_list',
	'List branches in a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/branches`, pageQuery({ page, limit }))),
);

registerTool(
	'git_branch_get',
	'Get a specific branch',
	{ ...OwnerRepo, branch: z.string().describe('Branch name'), ...ConnectionParam },
	async ({ owner, repo, branch, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/branches/${enc(branch)}`)),
);

registerTool(
	'git_branch_create',
	'Create a new branch',
	{
		...OwnerRepo,
		new_branch_name: z.string().describe('Name for new branch'),
		old_branch_name: z.string().optional().describe('Source branch (default: default branch). STRICT REFS (#236): a bare channel name (stable/dev/rc/…) that exists as BOTH a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> or refs/tags/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		...ConnectionParam,
	},
	async ({ owner, repo, new_branch_name, old_branch_name, connection }) => {
		const client = clientFor(connection);
		const blocked = await assertRefsUnambiguous(client, owner, repo, [old_branch_name]);
		if (blocked) return blocked;
		const body: Record<string, unknown> = { new_branch_name };
		if (old_branch_name) body.old_branch_name = normalizeRef(old_branch_name);
		return formatResponse(await client.post(`/repos/${enc(owner)}/${enc(repo)}/branches`, body));
	},
);

registerTool(
	'git_branch_delete',
	'Delete a branch',
	{ ...OwnerRepo, branch: z.string().describe('Branch name'), ...ConnectionParam },
	async ({ owner, repo, branch, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/branches/${enc(branch)}`)),
);

// ── Commits ─────────────────────────────────────────────────────────────

registerTool(
	'git_commits_list',
	'List commits in a repository',
	{
		...OwnerRepo,
		sha: z.string().optional().describe('Branch or commit SHA.' + STRICT_REF_NOTE),
		path: z.string().optional().describe('Filter by file path'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, sha, path, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (sha) params['sha'] = sha;
		if (path) params['path'] = path;
		return getWithRefGuard(connection, owner, repo, [sha], `/repos/${enc(owner)}/${enc(repo)}/commits`, params);
	},
);

registerTool(
	'git_commit_get',
	'Get a specific commit',
	{ ...OwnerRepo, sha: z.string().describe('Commit SHA'), ...ConnectionParam },
	async ({ owner, repo, sha, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/git/commits/${enc(sha)}`)),
);

// ── Issues ──────────────────────────────────────────────────────────────

registerTool(
	'git_issues_list',
	'List issues in a repository',
	{
		...OwnerRepo,
		state: z.enum(['open', 'closed', 'all']).optional().describe('Issue state filter'),
		type: z.enum(['issues', 'pulls']).optional().describe('Filter by type'),
		labels: z.string().optional().describe('Comma-separated label names'),
		milestones: z.string().optional().describe('Comma-separated milestone names'),
		q: z.string().optional().describe('Search query'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, state, type, labels, milestones, q, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (state) params['state'] = state;
		if (type) params['type'] = type;
		if (labels) params['labels'] = labels;
		if (milestones) params['milestones'] = milestones;
		if (q) params['q'] = q;
		return formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues`, params));
	},
);

registerTool(
	'git_issue_get',
	'Get a single issue by number',
	{ ...OwnerRepo, number: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, number, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}`)),
);

registerTool(
	'git_issue_create',
	'Create a new issue. Status, priority and type are REQUIRED (MokoGIT #1808 — they are first-class fields that must be set explicitly on every create; omitting them to inherit org defaults is no longer allowed). Supply each as EITHER the numeric *_id OR the human *_name (e.g. status_name:"Resolved", priority_name:"High", type_name:"Bug") — names are resolved against the org definitions, case-insensitively. Discover valid values with git_org_issue_statuses_list / git_org_issue_priorities_list / git_org_issue_types_list. Before creating, this searches the repo for a likely-duplicate OPEN or CLOSED issue by title (and identical body); if one is found it returns the candidates and does NOT create — review them and either comment on / update the existing issue, reopen it if it regressed, or re-run with skip_dedupe_check=true to create anyway.',
	{
		...OwnerRepo,
		title: z.string().describe('Issue title'),
		body: z.string().optional().describe('Issue body (markdown)'),
		labels: z.array(z.union([z.number(), z.string()])).optional().describe('Label IDs or names (use git_labels_list to discover available labels)'),
		milestone: z.number().optional().describe('Milestone ID'),
		assignees: z.array(z.string()).optional().describe('Usernames to assign'),
		status_id: z.number().int().positive().optional().describe('REQUIRED (MokoGIT #1808) unless status_name is given. Issue status definition ID (use git_org_issue_statuses_list to discover).'),
		status_name: z.string().optional().describe('Alternative to status_id: the status name (e.g. "Resolved"), resolved against the org definitions. Pass exactly one of status_id/status_name.'),
		priority_id: z.number().int().positive().optional().describe('REQUIRED (MokoGIT #1808) unless priority_name is given. Issue priority definition ID (use git_org_issue_priorities_list to discover).'),
		priority_name: z.string().optional().describe('Alternative to priority_id: the priority name (e.g. "High"), resolved against the org definitions. Pass exactly one of priority_id/priority_name.'),
		type_id: z.number().int().positive().optional().describe('REQUIRED (MokoGIT #1808) unless type_name is given. Issue type definition ID (use git_org_issue_types_list to discover).'),
		type_name: z.string().optional().describe('Alternative to type_id: the type name (e.g. "Bug"), resolved against the org definitions. Pass exactly one of type_id/type_name.'),
		skip_dedupe_check: z.boolean().optional().describe('Set true to bypass the duplicate-issue guardrail and create even if a similar issue exists — use only after reviewing the candidates the guardrail returned.'),
		...ConnectionParam,
	},
	async ({ owner, repo, title, body: issueBody, labels, milestone, assignees, status_id, status_name, priority_id, priority_name, type_id, type_name, skip_dedupe_check, connection }) => {
		const client = clientFor(connection);
		// Duplicate guardrail (MokoGIT #1415): search existing OPEN+CLOSED issues by
		// the title keywords and flag a likely duplicate before creating a new one.
		if (!skip_dedupe_check) {
			const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
			const nTitle = norm(title);
			const nBody = issueBody ? norm(issueBody) : '';
			const search = await client.get(`/repos/${enc(owner)}/${enc(repo)}/issues`, { q: title, state: 'all', type: 'issues', limit: '30' });
			if (search.status < 400 && Array.isArray(search.data)) {
				const candidates = (search.data as Array<Record<string, unknown>>)
					.filter((it) => {
						const t = norm(String(it.title ?? ''));
						if (!t) return false;
						if (t === nTitle) return true; // identical title (normalized)
						if (nTitle.length >= 6 && (t.includes(nTitle) || nTitle.includes(t))) return true; // one contains the other
						if (nBody && it.body && norm(String(it.body)) === nBody) return true; // identical body
						return false;
					})
					.map((it) => ({ number: it.number, title: it.title, state: it.state, html_url: it.html_url }));
				if (candidates.length > 0) {
					return {
						content: [{
							type: 'text' as const,
							text: JSON.stringify({
								possible_duplicate: true,
								message: `Found ${candidates.length} existing issue(s) that look like duplicates of "${title}". No issue was created. Review them, then either comment on / update the existing issue (git_issue_comment_create / git_issue_update), reopen it if it regressed, or re-run git_issue_create with skip_dedupe_check=true to create a new one anyway.`,
								candidates,
							}, null, 2),
						}],
					};
				}
			}
		}
		// status / priority / type are REQUIRED (MokoGIT #1808) — each supplied as
		// an *_id OR an *_name. The zod schema can't express "exactly one of a
		// pair" so guard at runtime: a family is missing only when NEITHER its id
		// nor its name was given (so omission errors explicitly instead of
		// silently inheriting org defaults).
		const missing = [
			status_id === undefined && status_name === undefined ? 'status (status_id or status_name)' : null,
			priority_id === undefined && priority_name === undefined ? 'priority (priority_id or priority_name)' : null,
			type_id === undefined && type_name === undefined ? 'type (type_id or type_name)' : null,
		].filter(Boolean);
		if (missing.length > 0) {
			return errorContent(`${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} required (MokoGIT #1808). Supply each as an id or a name — discover values with git_org_issue_statuses_list / git_org_issue_priorities_list / git_org_issue_types_list.`);
		}
		// Resolve any *_name to its numeric *_id against the org definitions.
		const resolved = await resolveIssueMeta(connection, owner, { status_id, status_name, priority_id, priority_name, type_id, type_name });
		if ('error' in resolved) return errorContent(resolved.error);
		const body: Record<string, unknown> = { title, status_id: resolved.status_id, priority_id: resolved.priority_id, type_id: resolved.type_id };
		if (issueBody) body.body = issueBody;
		if (labels) body.labels = labels;
		if (milestone) body.milestone = milestone;
		if (assignees) body.assignees = assignees;
		return formatResponse(await client.post(`/repos/${enc(owner)}/${enc(repo)}/issues`, body));
	},
);

registerTool(
	'git_issue_update',
	'Update an issue (supports title, body, state, assignees, milestone, and org-level metadata). Status/priority/type may be set by numeric *_id OR by human *_name (e.g. status_name:"Resolved"); to CLEAR one, pass its *_id as 0 (a name cannot clear).',
	{
		...OwnerRepo,
		number: z.number().describe('Issue number'),
		title: z.string().optional().describe('New title'),
		body: z.string().optional().describe('New body'),
		state: z.enum(['open', 'closed']).optional().describe('State'),
		assignees: z.array(z.string()).optional().describe('Assignees'),
		milestone: z.number().optional().describe('Milestone ID'),
		status_id: z.number().optional().describe('Issue status definition ID (use git_org_issue_statuses_list to discover; 0 to clear). Alternative: status_name.'),
		status_name: z.string().optional().describe('Set the status by name (e.g. "Resolved"), resolved against the org definitions. Pass status_id OR status_name, not both.'),
		priority_id: z.number().optional().describe('Issue priority definition ID (use git_org_issue_priorities_list to discover; 0 to clear). Alternative: priority_name.'),
		priority_name: z.string().optional().describe('Set the priority by name (e.g. "High"), resolved against the org definitions. Pass priority_id OR priority_name, not both.'),
		type_id: z.number().optional().describe('Issue type definition ID (use git_org_issue_types_list to discover; 0 to clear). Alternative: type_name.'),
		type_name: z.string().optional().describe('Set the type by name (e.g. "Bug"), resolved against the org definitions. Pass type_id OR type_name, not both.'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, title, body: issueBody, state, assignees, milestone, status_id, status_name, priority_id, priority_name, type_id, type_name, connection }) => {
		const resolved = await resolveIssueMeta(connection, owner, { status_id, status_name, priority_id, priority_name, type_id, type_name });
		if ('error' in resolved) return errorContent(resolved.error);
		const body: Record<string, unknown> = {};
		if (title !== undefined) body.title = title;
		if (issueBody !== undefined) body.body = issueBody;
		if (state) body.state = state;
		if (assignees) body.assignees = assignees;
		if (milestone !== undefined) body.milestone = milestone;
		if (resolved.status_id !== undefined) body.status_id = resolved.status_id;
		if (resolved.priority_id !== undefined) body.priority_id = resolved.priority_id;
		if (resolved.type_id !== undefined) body.type_id = resolved.type_id;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}`, body));
	},
);

registerTool(
	'git_issue_set_status',
	'Set or clear the status on an issue, by numeric status_id OR by status_name (e.g. "Resolved"). A status whose closes_issue is true (Resolved, Closed, Duplicate, etc.) also closes the ticket; a non-closing status reopens a closed ticket. Returns the updated issue with its resulting open/closed state.',
	{
		...OwnerRepo,
		number: z.number().describe('Issue number'),
		status_id: z.number().optional().describe('Status definition ID (0 to clear). Alternative: status_name.'),
		status_name: z.string().optional().describe('Status name (e.g. "Resolved"), resolved against the org definitions. Pass status_id OR status_name, not both (a name cannot clear — use status_id:0).'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, status_id, status_name, connection }) => {
		if (status_id === undefined && status_name === undefined) return errorContent('Provide status_id or status_name.');
		const resolved = await resolveIssueMeta(connection, owner, { status_id, status_name });
		if ('error' in resolved) return errorContent(resolved.error);
		const sId = resolved.status_id as number;
		const client = clientFor(connection);
		const setRes = await client.patch(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}`, { status_id: sId });
		if (setRes.status >= 400) return formatResponse(setRes);
		// Clearing the status (0) has no open/close semantics.
		if (!sId) return formatResponse(setRes);
		// Drive the ticket open/closed to match the status def's closes_issue:
		// a terminal status (Resolved/Closed/…) closes the ticket in ONE call;
		// a non-closing status reopens a closed ticket. Belt-and-suspenders for
		// forges before MokoGIT #1726 and a no-op once the forge syncs state
		// itself (state already matches → skip). Fail-open on any lookup error.
		try {
			const issue = setRes.data as { state?: string };
			const statusesRes = await clientV2For(connection).get(`/orgs/${enc(owner)}/issue-statuses`);
			const defs = statusesRes.status < 400 && Array.isArray(statusesRes.data)
				? (statusesRes.data as Array<{ id?: number; closes_issue?: boolean }>)
				: [];
			const def = defs.find((s) => s.id === sId);
			if (def) {
				const isClosed = issue.state === 'closed';
				let targetState: 'open' | 'closed' | undefined;
				if (def.closes_issue && !isClosed) targetState = 'closed';
				else if (!def.closes_issue && isClosed) targetState = 'open';
				if (targetState) {
					return formatResponse(await client.patch(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}`, { state: targetState }));
				}
			}
		} catch {
			/* fail-open: return the set-status result */
		}
		return formatResponse(setRes);
	},
);

registerTool(
	'git_issue_set_priority',
	'Set or clear the priority on an issue, by numeric priority_id OR by priority_name (e.g. "High"). Convenience wrapper around issue update.',
	{
		...OwnerRepo,
		number: z.number().describe('Issue number'),
		priority_id: z.number().optional().describe('Priority definition ID (0 to clear). Alternative: priority_name.'),
		priority_name: z.string().optional().describe('Priority name (e.g. "High"), resolved against the org definitions. Pass priority_id OR priority_name, not both (a name cannot clear — use priority_id:0).'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, priority_id, priority_name, connection }) => {
		if (priority_id === undefined && priority_name === undefined) return errorContent('Provide priority_id or priority_name.');
		const resolved = await resolveIssueMeta(connection, owner, { priority_id, priority_name });
		if ('error' in resolved) return errorContent(resolved.error);
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}`, { priority_id: resolved.priority_id }));
	},
);

registerTool(
	'git_issue_set_type',
	'Set or clear the type on an issue, by numeric type_id OR by type_name (e.g. "Bug"). Convenience wrapper around issue update.',
	{
		...OwnerRepo,
		number: z.number().describe('Issue number'),
		type_id: z.number().optional().describe('Type definition ID (0 to clear). Alternative: type_name.'),
		type_name: z.string().optional().describe('Type name (e.g. "Bug"), resolved against the org definitions. Pass type_id OR type_name, not both (a name cannot clear — use type_id:0).'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, type_id, type_name, connection }) => {
		if (type_id === undefined && type_name === undefined) return errorContent('Provide type_id or type_name.');
		const resolved = await resolveIssueMeta(connection, owner, { type_id, type_name });
		if ('error' in resolved) return errorContent(resolved.error);
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}`, { type_id: resolved.type_id }));
	},
);

registerTool(
	'git_issue_comments_list',
	'List comments on an issue',
	{ ...OwnerRepo, number: z.number().describe('Issue number'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, number, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}/comments`, pageQuery({ page, limit }))),
);

registerTool(
	'git_issue_comment_create',
	'Add a comment to an issue',
	{
		...OwnerRepo,
		number: z.number().describe('Issue number'),
		body: z.string().describe('Comment body (markdown)'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, body: commentBody, connection }) => {
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}/comments`, { body: commentBody }));
	},
);

registerTool(
	'git_issue_search',
	'Search issues across all repositories',
	{
		q: z.string().describe('Search query'),
		state: z.enum(['open', 'closed', 'all']).optional().describe('State filter'),
		labels: z.string().optional().describe('Comma-separated label IDs or names'),
		type: z.enum(['issues', 'pulls']).optional().describe('Filter type'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ q, state, labels, type, page, limit, connection }) => {
		const params: Record<string, string> = { q, ...pageQuery({ page, limit }) };
		if (state) params['state'] = state;
		if (labels) params['labels'] = labels;
		if (type) params['type'] = type;
		return formatResponse(await clientFor(connection).get('/repos/issues/search', params));
	},
);

// ── Labels ──────────────────────────────────────────────────────────────

registerTool(
	'git_labels_list',
	'List all labels in a repository (includes id, name, color, description - use to discover available type/priority/status labels)',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/labels`, pageQuery({ page, limit }))),
);

registerTool(
	'git_label_create',
	'Create a label',
	{
		...OwnerRepo,
		name: z.string().describe('Label name'),
		color: z.string().describe('Color hex (e.g. "#d73a4a")'),
		description: z.string().optional().describe('Label description'),
		...ConnectionParam,
	},
	async ({ owner, repo, name, color, description, connection }) => {
		const body: Record<string, unknown> = { name, color };
		if (description) body.description = description;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/labels`, body));
	},
);

// ── Milestones ──────────────────────────────────────────────────────────

registerTool(
	'git_milestones_list',
	'List milestones in a repository',
	{
		...OwnerRepo,
		state: z.enum(['open', 'closed', 'all']).optional().describe('State filter'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, state, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (state) params['state'] = state;
		return formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/milestones`, params));
	},
);

registerTool(
	'git_milestone_create',
	'Create a milestone',
	{
		...OwnerRepo,
		title: z.string().describe('Milestone title'),
		description: z.string().optional().describe('Description'),
		due_on: z.string().optional().describe('Due date (ISO 8601)'),
		...ConnectionParam,
	},
	async ({ owner, repo, title, description, due_on, connection }) => {
		const body: Record<string, unknown> = { title };
		if (description) body.description = description;
		if (due_on) body.due_on = due_on;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/milestones`, body));
	},
);

// ── Pull Requests ───────────────────────────────────────────────────────

registerTool(
	'git_pulls_list',
	'List pull requests',
	{
		...OwnerRepo,
		state: z.enum(['open', 'closed', 'all']).optional().describe('State filter'),
		sort: z.enum(['oldest', 'recentupdate', 'leastupdate', 'mostcomment', 'leastcomment', 'priority']).optional(),
		labels: z.string().optional().describe('Comma-separated label IDs'),
		milestone: z.number().optional().describe('Milestone ID'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, state, sort, labels, milestone, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (state) params['state'] = state;
		if (sort) params['sort'] = sort;
		if (labels) params['labels'] = labels;
		if (milestone !== undefined) params['milestone'] = String(milestone);
		return formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls`, params));
	},
);

registerTool(
	'git_pull_get',
	'Get a single pull request',
	{ ...OwnerRepo, number: z.number().describe('PR number'), ...ConnectionParam },
	async ({ owner, repo, number, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}`)),
);

registerTool(
	'git_pull_create',
	'Create a pull request',
	{
		...OwnerRepo,
		title: z.string().describe('PR title'),
		head: z.string().describe('Source branch. STRICT REFS (#236): a bare channel name that is both a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		base: z.string().describe('Target branch. STRICT REFS (#236): a bare channel name that is both a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		cascade_mode: z.enum(['inherit', 'off', 'notify', 'auto_merge', 'auto_resolve']).describe('Required. How downstream channel branches are handled when this PR merges: inherit (repo default), off, notify, auto_merge, or auto_resolve.'),
		body: z.string().optional().describe('PR description (markdown)'),
		labels: z.array(z.union([z.number(), z.string()])).optional().describe('Label IDs or names (use git_labels_list to discover available labels)'),
		milestone: z.number().optional().describe('Milestone ID'),
		assignees: z.array(z.string()).optional().describe('Assignees'),
		...ConnectionParam,
	},
	async ({ owner, repo, title, head, base, cascade_mode, body: prBody, labels, milestone, assignees, connection }) => {
		const client = clientFor(connection);
		const blocked = await assertRefsUnambiguous(client, owner, repo, [base, head]);
		if (blocked) return blocked;
		const body: Record<string, unknown> = { title, head: normalizeRef(head), base: normalizeRef(base), cascade_mode };
		if (prBody) body.body = prBody;
		if (labels) body.labels = labels;
		if (milestone) body.milestone = milestone;
		if (assignees) body.assignees = assignees;
		return formatResponse(await client.post(`/repos/${enc(owner)}/${enc(repo)}/pulls`, body));
	},
);

// ── Pre-merge CI gate (mokogit-mcp #287) ──────────────────────────────────
//
// Before pull_merge POSTs the merge, resolve the PR head SHA and investigate
// its workflow runs (run → job → step → log), classifying every red as a REAL
// code-check failure vs. an environmental step-0/checkout abort vs. an infra
// HTTP 422/500 bump race (see source/premerge-ci.ts). The default policy
// ('real') blocks only on a CONFIRMED real failure — honouring the org rule
// that CI is advisory, not a hard gate — and a force+reason bypass is always
// available. All the investigation/classification logic lives in the separate
// premerge-ci module so this hook stays a few lines and does NOT collide with
// the sibling rapid-merge guard (#288), which edits this same handler body.
//
// This resolves the head SHA via the PR object and is fail-open: if the PR
// cannot be read, the gate degrades to a reported no-op rather than blocking.

// Resolve a PR's head commit SHA (pull.head.sha). Returns null on any error.
async function resolvePrHeadSha(
	client: GitClient,
	owner: string,
	repo: string,
	number: number,
): Promise<string | null> {
	try {
		const res = await client.get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}`);
		if (res.status >= 400) return null;
		const head = (res.data as { head?: { sha?: unknown } } | null)?.head;
		return head && typeof head.sha === 'string' ? head.sha : null;
	} catch {
		return null;
	}
}

// Shared schema fields for the #287 gate, used by both pull_merge and the
// standalone pull_preflight tool so the knobs stay identical.
const PremergeGateParams = {
	require_green: z
		.enum(['off', 'advisory', 'real', 'strict'])
		.optional()
		.describe('Pre-merge CI gate policy (default "real"). off = skip the gate; advisory = investigate + report but never block; real = block ONLY on a confirmed real code/lint/test failure at the head SHA (environmental step-0 aborts and infra 422/500 bump races are allowed + reported); strict = block on ANY red or on no-CI-found. Honours the org rule that CI is advisory, not a hard gate.'),
	force: z
		.boolean()
		.optional()
		.describe('Bypass a pre-merge CI block. Requires force_reason. Distinct from force_merge (which is the server-side admin status-check override).'),
	force_reason: z
		.string()
		.optional()
		.describe('Audit reason required when force=true bypasses a pre-merge CI block. Recorded in the returned report.'),
};

registerTool(
	'git_pull_merge',
	'Merge a pull request. Runs a pre-merge CI gate (#287) first: resolves the PR head SHA, investigates its workflow runs (run→job→step→log), classifies each red as real / environmental / infra, and blocks only on a CONFIRMED real failure (policy "real", default) unless force+force_reason is given. Set require_green to off/advisory/real/strict. On success returns a STRUCTURED object ({ok, merged, pull_request, merge_method, merge_commit_sha?}) rather than Gitea’s empty body, so callers no longer need a follow-up pull_get to confirm.',
	{
		...OwnerRepo,
		number: z.number().describe('PR number'),
		merge_type: z.enum(['merge', 'rebase', 'squash', 'rebase-merge']).optional().describe('Merge method (default: merge)'),
		title: z.string().optional().describe('Custom merge commit title'),
		message: z.string().optional().describe('Custom merge commit message'),
		delete_branch_after_merge: z.boolean().optional().describe('Delete head branch after merge'),
		force_merge: z.boolean().optional().describe('Admin override: merge past failing/missing required status checks (requires repo/org admin and block_admin_merge_override=false). Mirrors the web UI "Merge without waiting for status checks to succeed" control. Does not bypass merge conflicts or a WIP/closed PR.'),
		force_merge_reason: z.string().optional().describe('Audit reason recorded on the merge commit when force_merge is used (MokoGIT records it as a Force-merge-reason: trailer). Ignored unless force_merge is true.'),
		cascade: z.enum(['inherit', 'off', 'notify', 'auto_merge', 'auto_resolve']).describe('REQUIRED (MokoGIT #1415): the cascade mode for this immediate merge — how downstream channel branches are handled when the PR merges. inherit = use the repo/rule default; off = no downstream PR; notify = open the downstream PR for a human; auto_merge = open + merge when conflict-free; auto_resolve = auto_merge plus server-side conflict resolution.'),
		rapid_merge_guard: z.enum(['settle', 'off']).or(z.string()).optional().describe('Rapid-merge guard mode (#288), serializes merges to the same (repo, base) and waits out the pre-release version-bump race: "settle" (default) holds until an in-flight pre-release/version-advance run on the base completes; "cooldown:<sec>" applies a fixed post-merge pause; "off" disables the guard. Falls back to MOKOGIT_RAPID_MERGE_GUARD then "settle".'),
		max_wait: z.number().optional().describe('Upper bound in seconds on how long the rapid-merge guard holds (settle poll window or cooldown clamp). Default 180. Ignored when the guard is off/forced.'),
		...PremergeGateParams,
		...ConnectionParam,
	},
	async ({ owner, repo, number, merge_type, title, message, delete_branch_after_merge, force_merge, force_merge_reason, cascade, rapid_merge_guard, max_wait, require_green, force, force_reason, connection }) => {
		const client = clientFor(connection);
		const policy: PremergePolicy = require_green ?? 'real';

		// ── Mergeability (#311) ─────────────────────────────────────────────
		// Read the PR's own mergeable state up front. The #287 CI gate only
		// answers "is CI green?"; it says nothing about whether the merge can
		// actually happen. We must NEVER let a green CI verdict be read as
		// "merge allowed" when the PR is not mergeable (conflict with base).
		const mergeStatus: MergeStatus = await fetchMergeStatus(client, owner, repo, number);

		// ── Pre-merge CI gate (#287) ────────────────────────────────────────
		// Investigate the head SHA once; block on a real failure (per policy)
		// unless force+reason, otherwise carry the report through as an advisory
		// banner. The gate NEVER sends any field to the merge API body.
		let banner: string | null = null;
		if (policy !== 'off') {
			const headSha = await resolvePrHeadSha(client, owner, repo, number);
			if (headSha) {
				let report: PremergeReport | null = null;
				try {
					report = await investigatePremergeCi(client, owner, repo, headSha);
				} catch {
					report = null; // fail-open: never block on the gate's own error
				}
				if (report) {
					const verdict = evaluatePremergeGate(report, policy, force ?? false, force_reason);
					if (verdict.blocked) {
						const text = [
							'Merge BLOCKED by the pre-merge CI gate (#287).',
							'',
							renderPremergeReport(report, verdict, mergeStatus, number),
							'',
							'To override: re-run with force=true and a force_reason explaining why the red is safe to merge past.',
						].join('\n');
						return { content: [{ type: 'text' as const, text }] };
					}
					banner = renderPremergeReport(report, verdict, mergeStatus, number);
				}
			}
		}
		// If the gate was off (or we could not render it), still surface the
		// mergeability line so the caller sees it before the merge is attempted.
		if (!banner) {
			banner = `Pre-merge mergeability check — ${renderMergeStatus(mergeStatus, number)}`;
		}

		// ── Mergeability refusal (#311) ─────────────────────────────────────
		// A conflict / closed / already-merged PR cannot be merged; the POST
		// would return Gitea's opaque "Please try again later". Refuse up front
		// with the resolved cause + next step instead of letting the caller read
		// a "merge allowed" CI line and retry a conflict indefinitely. This is
		// orthogonal to force_merge (an admin status-check override, which does
		// NOT resolve a merge conflict).
		const blockedReason = mergeBlockedReason(mergeStatus, number);
		if (blockedReason) {
			const text = [
				'Merge NOT attempted — the PR cannot be merged in its current state (#311).',
				'',
				`  ${blockedReason}`,
				'',
				banner,
			].join('\n');
			return { content: [{ type: 'text' as const, text }] };
		}

		const body: Record<string, unknown> = { Do: merge_type ?? 'merge' };
		if (title) body.MergeTitleField = title;
		if (message) body.MergeMessageField = message;
		if (delete_branch_after_merge !== undefined) body.delete_branch_after_merge = delete_branch_after_merge;
		if (force_merge !== undefined) body.force_merge = force_merge;
		if (force_merge_reason) body.force_merge_reason = force_merge_reason;
		body.cascade = cascade;

		const mergeEndpoint = `/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}/merge`;
		const doMerge = () => client.post(mergeEndpoint, body);

		// Format a merge response. On FAILURE (#311), re-read the PR and translate
		// the concrete cause — turning Gitea's opaque "Please try again later"
		// (its not-mergeable / "checking" string) into the resolved reason + next
		// step — instead of passing the raw string through. On success, carry the
		// advisory note (CI banner + mergeability + any guard note) as usual.
		const finishMerge = async (res: ApiResponse, note: string | null) => {
			if (res.status >= 400) {
				const freshStatus = await fetchMergeStatus(client, owner, repo, number);
				const translated = translateMergeFailure(res, freshStatus, number);
				const text = note ? `${note}\n\n${translated}` : translated;
				return { content: [{ type: 'text' as const, text }] };
			}
			// mokogit-mcp #338: Gitea's merge endpoint returns 200 with an EMPTY
			// body, which formatResponse rendered as a bare "" — ambiguous success
			// that forced callers to pull_get to confirm. Emit a STRUCTURED success
			// object instead. Re-read the PR (fail-open) to surface merged state +
			// merge_commit_sha; never let the confirmation read turn a real success
			// into an error.
			let merged: boolean | undefined;
			let mergeCommitSha: string | undefined;
			try {
				const pr = await client.get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}`);
				if (pr.status < 400 && pr.data && typeof pr.data === 'object') {
					const d = pr.data as { merged?: unknown; merge_commit_sha?: unknown };
					if (typeof d.merged === 'boolean') merged = d.merged;
					if (typeof d.merge_commit_sha === 'string' && d.merge_commit_sha) mergeCommitSha = d.merge_commit_sha;
				}
			} catch { /* fail-open: the merge POST already succeeded */ }
			const success = {
				ok: true,
				merged: merged ?? true,
				pull_request: number,
				merge_method: merge_type ?? 'merge',
				...(mergeCommitSha ? { merge_commit_sha: mergeCommitSha } : {}),
				status: res.status,
				message: `PR #${number} merged (${merge_type ?? 'merge'}).`,
			};
			const body = JSON.stringify(success, null, 2);
			const mergedText = note ? `${note}

${body}` : body;
			return { content: [{ type: 'text' as const, text: mergedText }] };
		};

		// Rapid-merge guard (#288): serialize + settle-wait per (repo, base) so
		// back-to-back merges don't race the pre-release version bump. Kept in its
		// own module so it stays clear of the #287 CI-gate edits to this handler.
		const cfg = resolveGuardConfig({ rapidMergeGuard: rapid_merge_guard, maxWait: max_wait, force });
		if (cfg.mode.kind === 'off') {
			return finishMerge(await doMerge(), banner);
		}

		// The guard keys on the PR's BASE branch. Reuse the base ref already read
		// for mergeability (#311); fall back to a fresh lookup. Fail-open: if the
		// base is unknown, merge unguarded rather than block on a probe error.
		let base: string | undefined = mergeStatus.base_ref ?? undefined;
		if (!base) {
			try {
				const pr = await client.get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}`);
				if (pr.status < 400) base = (pr.data as { base?: { ref?: string } })?.base?.ref;
			} catch { /* fail-open */ }
		}
		if (!base) {
			return finishMerge(await doMerge(), banner);
		}

		const { response, guardNote } = await runGuardedMerge({
			client, connection, owner, repo, base, cfg, doMerge,
		});
		const note = [banner, guardNote].filter(Boolean).join('\n\n') || null;
		return finishMerge(response, note);
	},
);

registerTool(
	'git_pull_preflight',
	'Pre-merge CI preflight (#287/#311): resolve a PR head SHA, list its workflow runs (confirming a run object EXISTS — "0 runs" is reported as "no CI found", never green), drill every red run into job→step→log, and return a structured, secret-redacted report classifying each failure as real / environmental (step-0 checkout abort, transient) / infra (HTTP 422/500 bump race). ALSO reports the PR\'s mergeable state (conflict with base / draft / checking) as a SEPARATE axis from CI — a green CI verdict never implies the merge will succeed. Returns the gate verdict for the given policy WITHOUT merging anything.',
	{
		...OwnerRepo,
		number: z.number().describe('PR number'),
		require_green: PremergeGateParams.require_green,
		force: PremergeGateParams.force,
		force_reason: PremergeGateParams.force_reason,
		...ConnectionParam,
	},
	async ({ owner, repo, number, require_green, force, force_reason, connection }) => {
		const client = clientFor(connection);
		const policy: PremergePolicy = require_green ?? 'real';
		// Mergeability (#311): read the PR's own mergeable state alongside CI.
		const mergeStatus = await fetchMergeStatus(client, owner, repo, number);
		const headSha = await resolvePrHeadSha(client, owner, repo, number);
		if (!headSha) {
			return { content: [{ type: 'text' as const, text: `Pre-merge preflight: could not resolve the head SHA for PR #${number} (PR not found or not readable).\n\n  ${renderMergeStatus(mergeStatus, number)}` }] };
		}
		const report = await investigatePremergeCi(client, owner, repo, headSha);
		const verdict = evaluatePremergeGate(report, policy, force ?? false, force_reason);
		const text = `${renderPremergeReport(report, verdict, mergeStatus, number)}\n\n${JSON.stringify({ report, verdict, mergeStatus }, null, 2)}`;
		return { content: [{ type: 'text' as const, text }] };
	},
);

registerTool(
	'git_pull_files',
	'List files changed in a pull request',
	{ ...OwnerRepo, number: z.number().describe('PR number'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, number, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}/files`, pageQuery({ page, limit }))),
);

registerTool(
	'git_pull_review_create',
	'Create a pull request review',
	{
		...OwnerRepo,
		number: z.number().describe('PR number'),
		event: z.enum(['APPROVED', 'REQUEST_CHANGES', 'COMMENT']).describe('Review action'),
		body: z.string().optional().describe('Review comment'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, event, body: reviewBody, connection }) => {
		const body: Record<string, unknown> = { event };
		if (reviewBody) body.body = reviewBody;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}/reviews`, body));
	},
);

// ── Releases ────────────────────────────────────────────────────────────

registerTool(
	'git_releases_list',
	'List releases',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/releases`, pageQuery({ page, limit }))),
);

registerTool(
	'git_release_get',
	'Get a single release by ID',
	{ ...OwnerRepo, id: z.number().describe('Release ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/releases/${enc(id)}`)),
);

registerTool(
	'git_release_latest',
	'Get the latest release',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/releases/latest`)),
);

registerTool(
	'git_release_create',
	'Create a new release',
	{
		...OwnerRepo,
		tag_name: z.string().describe('Tag name (e.g. "v1.0.0")'),
		name: z.string().optional().describe('Release title'),
		body: z.string().optional().describe('Release notes (markdown)'),
		target_commitish: z.string().optional().describe('Target branch/commit'),
		draft: z.boolean().optional().describe('Create as draft'),
		prerelease: z.boolean().optional().describe('Mark as prerelease'),
		...ConnectionParam,
	},
	async ({ owner, repo, tag_name, name, body: notes, target_commitish, draft, prerelease, connection }) => {
		const body: Record<string, unknown> = { tag_name };
		if (name) body.name = name;
		if (notes) body.body = notes;
		if (target_commitish) body.target_commitish = target_commitish;
		if (draft !== undefined) body.draft = draft;
		if (prerelease !== undefined) body.prerelease = prerelease;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/releases`, body));
	},
);

registerTool(
	'git_release_delete',
	'Delete a release',
	{ ...OwnerRepo, id: z.number().describe('Release ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/releases/${enc(id)}`)),
);

registerTool(
	'git_release_lock',
	'Lock a release so retention pruning (#1776) never removes it. Requires the manage_release_locks permission (site admin, repo owner/admin, or a team granted the capability) — NOT ordinary release-write. Returns the updated release (prune_locked=true).',
	{ ...OwnerRepo, id: z.number().describe('Release ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/releases/${enc(id)}/prune-lock`, {})),
);

registerTool(
	'git_release_unlock',
	'Unlock a release so it is again subject to retention pruning (#1776). Requires the manage_release_locks permission. Returns the updated release (prune_locked=false).',
	{ ...OwnerRepo, id: z.number().describe('Release ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/releases/${enc(id)}/prune-lock`)),
);

// ── Tags ────────────────────────────────────────────────────────────────

registerTool(
	'git_tags_list',
	'List tags',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/tags`, pageQuery({ page, limit }))),
);

registerTool(
	'git_tag_create',
	'Create a tag',
	{
		...OwnerRepo,
		tag_name: z.string().describe('Tag name'),
		target: z.string().optional().describe('Target branch/commit SHA. STRICT REFS (#236): a bare channel name that is both a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> or refs/tags/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		message: z.string().optional().describe('Tag message (annotated tag)'),
		...ConnectionParam,
	},
	async ({ owner, repo, tag_name, target, message, connection }) => {
		const client = clientFor(connection);
		const blocked = await assertRefsUnambiguous(client, owner, repo, [target]);
		if (blocked) return blocked;
		const body: Record<string, unknown> = { tag_name };
		if (target) body.target = normalizeRef(target);
		if (message) body.message = message;
		return formatResponse(await client.post(`/repos/${enc(owner)}/${enc(repo)}/tags`, body));
	},
);

registerTool(
	'git_tag_delete',
	'Delete a tag',
	{ ...OwnerRepo, tag: z.string().describe('Tag name'), ...ConnectionParam },
	async ({ owner, repo, tag, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/tags/${enc(tag)}`)),
);

// ── Actions (CI/CD) ─────────────────────────────────────────────────────

registerTool(
	'git_actions_runs_list',
	'List workflow runs for a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runs`, pageQuery({ page, limit }))),
);

registerTool(
	'git_actions_run_get',
	'Get a specific workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), ...ConnectionParam },
	async ({ owner, repo, run_id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}`)),
);

registerTool(
	'git_actions_dispatch',
	'Trigger a workflow dispatch (e.g. pre-release, deploy)',
	{
		...OwnerRepo,
		workflow: z.string().describe('Workflow filename (e.g. pre-release.yml)'),
		ref: z.string().describe('Branch or tag to run on (e.g. dev, main)'),
		inputs: z.record(z.string()).optional().describe('Workflow input key-value pairs'),
		...ConnectionParam,
	},
	async ({ owner, repo, workflow, ref, inputs, connection }) =>
		formatResponse(await clientFor(connection).post(
			`/repos/${enc(owner)}/${enc(repo)}/actions/workflows/${enc(workflow)}/dispatches`,
			{ ref, inputs: inputs ?? {} },
		)),
);

registerTool(
	'git_actions_jobs_list',
	'List jobs for a workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), ...ConnectionParam },
	async ({ owner, repo, run_id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}/jobs`)),
);

registerTool(
	'git_actions_job_logs',
	'Get log output for a workflow job',
	{ ...OwnerRepo, job_id: z.number().describe('Job ID'), ...ConnectionParam },
	async ({ owner, repo, job_id, connection }) => {
		const client = clientFor(connection);
		const res = await client.get(`/repos/${enc(owner)}/${enc(repo)}/actions/jobs/${enc(job_id)}/logs`);
		if (res.status >= 400) return formatResponse(res);
		// Logs come as plain text
		const text = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
		return { content: [{ type: 'text' as const, text }] };
	},
);

registerTool(
	'git_release_asset_upload',
	'Upload a file as a release asset (provide base64-encoded content)',
	{
		...OwnerRepo,
		release_id: z.number().describe('Release ID'),
		name: z.string().describe('Asset filename'),
		content_base64: z.string().describe('Base64-encoded file content'),
		...ConnectionParam,
	},
	async ({ owner, repo, release_id, name, content_base64, connection }) => {
		const conn = getConnection(config, connection);
		const buf = Buffer.from(content_base64, 'base64');
		const res = await uploadBinary(conn, `/repos/${enc(owner)}/${enc(repo)}/releases/${enc(release_id)}/assets`, { name }, buf);
		return formatResponse(res);
	},
);

registerTool(
	'git_release_asset_delete',
	'Delete a release asset',
	{
		...OwnerRepo,
		release_id: z.number().describe('Release ID'),
		asset_id: z.number().describe('Asset ID'),
		...ConnectionParam,
	},
	async ({ owner, repo, release_id, asset_id, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/releases/${enc(release_id)}/assets/${enc(asset_id)}`)),
);

registerTool(
	'git_bulk_file_push',
	'Push the same file content to multiple repos (uses Contents API)',
	{
		owner: z.string().describe('Organization name'),
		repos: z.array(z.string()).describe('List of repository names'),
		path: z.string().describe('File path in each repo (e.g. .mokogit/workflows/pre-release.yml)'),
		content_base64: z.string().describe('Base64-encoded file content'),
		message: z.string().describe('Commit message'),
		branch: z.string().optional().describe('Target branch (default: main)'),
		...ConnectionParam,
	},
	async ({ owner, repos, path, content_base64, message, branch, connection }) => {
		const client = clientFor(connection);
		const targetBranch = branch ?? 'main';
		const results: Array<{ repo: string; status: string }> = [];

		for (const repo of repos) {
			try {
				const contentsPath = `/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(path)}`;
				// Get current file SHA
				const existing = await client.get(`${contentsPath}?ref=${enc(targetBranch)}`);
				const sha = (existing.data as { sha?: string })?.sha;

				if (sha) {
					// Update existing file
					await client.put(contentsPath, {
						content: content_base64,
						sha,
						message,
						branch: targetBranch,
					});
					results.push({ repo, status: 'updated' });
				} else {
					// Create new file
					await client.put(contentsPath, {
						content: content_base64,
						message,
						branch: targetBranch,
					});
					results.push({ repo, status: 'created' });
				}
			} catch (e) {
				results.push({ repo, status: `error: ${e}` });
			}
		}

		const summary = results.map(r => `${r.repo}: ${r.status}`).join('\n');
		return { content: [{ type: 'text' as const, text: summary }] };
	},
);

// ── Organizations ───────────────────────────────────────────────────────

registerTool(
	'git_org_get',
	'Get organization details',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}`)),
);

registerTool(
	'git_org_teams_list',
	'List teams in an organization',
	{ org: z.string().describe('Organization name'), ...PaginationParams, ...ConnectionParam },
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/teams`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_members_list',
	'List members of an organization',
	{ org: z.string().describe('Organization name'), ...PaginationParams, ...ConnectionParam },
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/members`, pageQuery({ page, limit }))),
);

// ── Organization Issue Metadata ──────────────────────────────────────────

registerTool(
	'git_org_issue_statuses_list',
	'List issue status definitions for an organization (id, name, color, closes_issue - use to discover valid status_id values)',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/issue-statuses`)),
);

registerTool(
	'git_org_issue_status_create',
	'Create an org issue status definition. closes_issue sets the open/close tie: a status with closes_issue=true closes the ticket when applied (a non-closing status reopens a closed one). Org-owner only.',
	{
		org: z.string().describe('Organization name'),
		name: z.string().describe('Status name (e.g. In Progress, Resolved)'),
		color: z.string().optional().describe('Hex color, e.g. #16a34a'),
		description: z.string().optional().describe('Help text shown to users'),
		closes_issue: z.boolean().optional().describe('If true, applying this status closes the ticket (and a non-closing status reopens a closed one)'),
		sort_order: z.number().optional().describe('Display sort order'),
		...ConnectionParam,
	},
	async ({ org, name, color, description, closes_issue, sort_order, connection }) => {
		const body: Record<string, unknown> = { name };
		if (color !== undefined) body.color = color;
		if (description !== undefined) body.description = description;
		if (closes_issue !== undefined) body.closes_issue = closes_issue;
		if (sort_order !== undefined) body.sort_order = sort_order;
		return formatResponse(await clientV2For(connection).post(`/orgs/${enc(org)}/issue-statuses`, body));
	},
);

registerTool(
	'git_org_issue_status_edit',
	'Edit an org issue status definition (partial). Set closes_issue to change the open/close tie: true = applying it closes the ticket, false = reopens a closed ticket. Org-owner only.',
	{
		org: z.string().describe('Organization name'),
		id: z.number().describe('Status definition ID (from git_org_issue_statuses_list)'),
		name: z.string().optional().describe('New name'),
		color: z.string().optional().describe('New hex color'),
		description: z.string().optional().describe('New description'),
		closes_issue: z.boolean().optional().describe('Open/close tie: true closes the ticket when applied, false reopens a closed one'),
		is_active: z.boolean().optional().describe('Whether the status is active (shown/selectable)'),
		sort_order: z.number().optional().describe('New display sort order'),
		...ConnectionParam,
	},
	async ({ org, id, name, color, description, closes_issue, is_active, sort_order, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body.name = name;
		if (color !== undefined) body.color = color;
		if (description !== undefined) body.description = description;
		if (closes_issue !== undefined) body.closes_issue = closes_issue;
		if (is_active !== undefined) body.is_active = is_active;
		if (sort_order !== undefined) body.sort_order = sort_order;
		return formatResponse(await clientV2For(connection).patch(`/orgs/${enc(org)}/issue-statuses/${enc(id)}`, body));
	},
);

registerTool(
	'git_org_issue_status_delete',
	'Delete an org issue status definition (a required status cannot be deleted). Org-owner only.',
	{
		org: z.string().describe('Organization name'),
		id: z.number().describe('Status definition ID'),
		...ConnectionParam,
	},
	async ({ org, id, connection }) => formatResponse(await clientV2For(connection).delete(`/orgs/${enc(org)}/issue-statuses/${enc(id)}`)),
);

registerTool(
	'git_org_capabilities_list',
	'List the org-admin capabilities a team can be granted (key + description). The catalog for git_org_team_capabilities_set (#1760 teams-as-permission-groups).',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/capabilities`)),
);

registerTool(
	'git_org_team_capabilities_get',
	"Get a team's delegated org-admin capabilities (the capability keys the team holds). Owner teams implicitly hold all.",
	{
		org: z.string().describe('Organization name'),
		team: z.string().describe('Team name/slug'),
		...ConnectionParam,
	},
	async ({ org, team, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/teams/${enc(team)}/capabilities`)),
);

registerTool(
	'git_org_team_capabilities_set',
	'Replace a team\'s delegated org-admin capabilities (full replace, not merge). Keys from git_org_capabilities_list; unknown keys are rejected. Cannot be set on the Owners team. Org-owner only.',
	{
		org: z.string().describe('Organization name'),
		team: z.string().describe('Team name/slug'),
		capabilities: z.array(z.string()).describe('Capability keys to grant, e.g. ["manage_webhooks","manage_secrets"] (replaces the current set)'),
		...ConnectionParam,
	},
	async ({ org, team, capabilities, connection }) =>
		formatResponse(await clientV2For(connection).put(`/orgs/${enc(org)}/teams/${enc(team)}/capabilities`, { capabilities })),
);

registerTool(
	'git_org_release_retention_get',
	"Get an organization's release version-retention policy (#1776): enabled, mode (keep_all/keep_last_n/keep_current_major/keep_last_n_per_major), keep_count, assets_only, apply_to_suborgs. Pruning is assets-only and never touches a channel-pointed release.",
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/release-retention`)),
);

registerTool(
	'git_org_release_retention_set',
	"Set an organization's release version-retention policy (#1776). mode is required. Server enforces assets-only pruning (keeps the immutable vNN tag + release + changelog) and never prunes a channel-pointed (stable/rc/development) release. Org-owner only.",
	{
		org: z.string().describe('Organization name'),
		mode: z.enum(['keep_all', 'keep_last_n', 'keep_current_major', 'keep_last_n_per_major']).describe('Retention mode (keep_all = no pruning)'),
		enabled: z.boolean().optional().describe('Enable pruning for this org (policy is off by default)'),
		keep_count: z.number().int().optional().describe('For keep_last_n / keep_last_n_per_major: how many newest versions to keep'),
		assets_only: z.boolean().optional().describe('Prune only release assets, keeping tag+release+changelog (default true; false is not yet supported server-side)'),
		apply_to_suborgs: z.boolean().optional().describe('Apply this policy to sub-organizations'),
		...ConnectionParam,
	},
	async ({ org, mode, enabled, keep_count, assets_only, apply_to_suborgs, connection }) => {
		const body: Record<string, unknown> = { mode };
		if (enabled !== undefined) body.enabled = enabled;
		if (keep_count !== undefined) body.keep_count = keep_count;
		if (assets_only !== undefined) body.assets_only = assets_only;
		if (apply_to_suborgs !== undefined) body.apply_to_suborgs = apply_to_suborgs;
		return formatResponse(await clientV2For(connection).put(`/orgs/${enc(org)}/release-retention`, body));
	},
);

registerTool(
	'git_org_issue_priorities_list',
	'List issue priority definitions for an organization (id, name, color, is_default - use to discover valid priority_id values)',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/issue-priorities`)),
);

registerTool(
	'git_org_issue_types_list',
	'List issue type definitions for an organization (id, name, color, is_default - use to discover valid type_id values)',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/issue-types`)),
);

// ── Users ───────────────────────────────────────────────────────────────

registerTool(
	'git_user_get',
	'Get a user profile',
	{ username: z.string().describe('Username'), ...ConnectionParam },
	async ({ username, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}`)),
);

registerTool(
	'git_users_search',
	'Search users',
	{
		q: z.string().describe('Search query'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ q, page, limit, connection }) => formatResponse(await clientFor(connection).get('/users/search', { q, ...pageQuery({ page, limit }) })),
);

// ── Webhooks ────────────────────────────────────────────────────────────

registerTool(
	'git_webhooks_list',
	'List webhooks for a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/hooks`, pageQuery({ page, limit }))),
);

registerTool(
	'git_webhook_create',
	'Create a webhook',
	{
		...OwnerRepo,
		type: z.enum(['git', 'slack', 'discord', 'dingtalk', 'telegram', 'msteams', 'feishu', 'matrix', 'wechatwork', 'packagist']).describe('Hook type'),
		url: z.string().describe('Webhook URL'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ owner, repo, type, url, events, active, connection }) => {
		const body: Record<string, unknown> = {
			type,
			config: { url, content_type: 'json' },
			events: events ?? ['push'],
			active: active ?? true,
		};
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/hooks`, body));
	},
);

// ── Wiki ────────────────────────────────────────────────────────────────

registerTool(
	'git_wiki_pages_list',
	'List wiki pages',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/wiki/pages`, pageQuery({ page, limit }))),
);

registerTool(
	'git_wiki_page_get',
	'Get a wiki page',
	{ ...OwnerRepo, page_name: z.string().describe('Page name/slug'), ...ConnectionParam },
	async ({ owner, repo, page_name, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/wiki/page/${encPath(page_name)}`)),
);

registerTool(
	'git_wiki_page_create',
	'Create a new wiki page',
	{
		...OwnerRepo,
		title: z.string().describe('Page title'),
		content: z.string().describe('Page content (markdown)'),
		message: z.string().optional().describe('Commit message for the wiki change'),
		...ConnectionParam,
	},
	async ({ owner, repo, title, content, message, connection }) => {
		const body: Record<string, unknown> = {
			title,
			content_base64: Buffer.from(content).toString('base64'),
		};
		if (message !== undefined) body.message = message;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/wiki/new`, body));
	},
);

registerTool(
	'git_wiki_page_edit',
	'Edit an existing wiki page',
	{
		...OwnerRepo,
		page_name: z.string().describe('Current page name/slug'),
		content: z.string().describe('New page content (markdown)'),
		title: z
			.string()
			.optional()
			.describe('New page title (only to rename). Omit to preserve the current page name for a content-only edit.'),
		message: z.string().optional().describe('Commit message for the wiki change'),
		...ConnectionParam,
	},
	async ({ owner, repo, page_name, content, title, message, connection }) => {
		const client = clientFor(connection);
		// Gitea's PATCH treats `title` as the page's NEW name. Omitting it (or
		// sending empty) renames the page to `unnamed`, so concurrent content-only
		// edits collide and overwrite each other. When the caller does not supply a
		// title, resolve the CURRENT page title so a content-only edit preserves the
		// name. Fall back to a title derived from page_name rather than send empty.
		//
		// #331 (follow-up to the #141/#142 fix): the GET response's `title` is only
		// the LEAF display name (e.g. "UPDATE SERVER") — it drops the folder for a
		// subdirectory page whose sub_url is e.g. "features/UPDATE-SERVER". Forwarding
		// that bare leaf as the new title makes Gitea slugify it back to TOP-LEVEL
		// (UserTitleToWebPath uses '/' as a folder separator), flattening the page out
		// of its folder and leaving the original path a 404. So for a nested page we
		// must re-qualify the resolved leaf title with its folder prefix, so the title
		// round-trips back to the same sub_url (verified: "features/UPDATE SERVER" ->
		// "features/UPDATE-SERVER"). The caller's explicit `title` is passed through
		// untouched (an intentional rename may itself carry a folder prefix).
		let resolvedTitle = title;
		if (resolvedTitle === undefined) {
			const current = await client.get(`/repos/${enc(owner)}/${enc(repo)}/wiki/page/${encPath(page_name)}`);
			const page = current.data as { title?: string; sub_url?: string } | undefined;
			const leafTitle =
				current.status < 400 && typeof page?.title === 'string' && page.title.length > 0
					? page.title
					: leafSlug(page_name).replace(/-/g, ' ');
			// Prefer the server's sub_url for the authoritative folder path; fall back
			// to the slash segments of page_name. qualifyWikiTitle returns the leaf
			// unchanged for a flat page (empty prefix) — no #141/#142 regression — and
			// "<folder>/<leaf>" for a nested page so Gitea keeps it in its folder.
			const folderSource = typeof page?.sub_url === 'string' && page.sub_url.length > 0 ? page.sub_url : page_name;
			resolvedTitle = qualifyWikiTitle(leafTitle, folderSource);
		}
		const body: Record<string, unknown> = {
			title: resolvedTitle,
			content_base64: Buffer.from(content).toString('base64'),
		};
		if (message !== undefined) body.message = message;
		return formatResponse(await client.patch(`/repos/${enc(owner)}/${enc(repo)}/wiki/page/${encPath(page_name)}`, body));
	},
);

registerTool(
	'git_wiki_page_delete',
	'Delete a wiki page',
	{
		...OwnerRepo,
		page_name: z.string().describe('Page name/slug to delete'),
		...ConnectionParam,
	},
	async ({ owner, repo, page_name, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/wiki/page/${encPath(page_name)}`)),
);

registerTool(
	'git_wiki_page_revisions',
	'List revision history for a wiki page',
	{ ...OwnerRepo, page_name: z.string().describe('Page name/slug'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page_name, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/wiki/revisions/${encPath(page_name)}`, pageQuery({ page, limit }))),
);

registerTool(
	'git_wiki_search',
	'Search wiki page titles and content',
	{ ...OwnerRepo, q: z.string().describe('Search query'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, q, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/wiki/search`, { q, ...pageQuery({ page, limit }) })),
);

// ── Notifications ───────────────────────────────────────────────────────

registerTool(
	'git_notifications_list',
	'List notifications for the authenticated user',
	{
		status_types: z.string().optional().describe('Comma-separated: read, unread, pinned'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ status_types, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (status_types) params['status-types'] = status_types;
		return formatResponse(await clientFor(connection).get('/notifications', params));
	},
);

registerTool(
	'git_notifications_read',
	'Mark all notifications as read',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).put('/notifications', { })),
);

// ── Topics ──────────────────────────────────────────────────────────────

registerTool(
	'git_repo_topics',
	'Get topics (tags) for a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/topics`)),
);

registerTool(
	'git_repo_topics_set',
	'Set topics for a repository (replaces all existing)',
	{
		...OwnerRepo,
		topics: z.array(z.string()).describe('Array of topic names'),
		...ConnectionParam,
	},
	async ({ owner, repo, topics, connection }) => formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/topics`, { topics })),
);

registerTool(
	'git_topic_search',
	'Search topics across all repositories',
	{
		q: z.string().describe('Search query'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ q, page, limit, connection }) => formatResponse(await clientFor(connection).get('/topics/search', { q, ...pageQuery({ page, limit }) })),
);

// ── Collaborators ───────────────────────────────────────────────────────

registerTool(
	'git_collaborators_list',
	'List collaborators on a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/collaborators`, pageQuery({ page, limit }))),
);

registerTool(
	'git_collaborator_add',
	'Add a collaborator to a repository',
	{
		...OwnerRepo,
		collaborator: z.string().describe('Username to add'),
		permission: z.enum(['read', 'write', 'admin']).optional().describe('Permission level (default: write)'),
		...ConnectionParam,
	},
	async ({ owner, repo, collaborator, permission, connection }) => {
		const body: Record<string, unknown> = {};
		if (permission) body.permission = permission;
		return formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/collaborators/${enc(collaborator)}`, body));
	},
);

registerTool(
	'git_collaborator_remove',
	'Remove a collaborator from a repository',
	{
		...OwnerRepo,
		collaborator: z.string().describe('Username to remove'),
		...ConnectionParam,
	},
	async ({ owner, repo, collaborator, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/collaborators/${enc(collaborator)}`)),
);

// ── Deploy Keys ─────────────────────────────────────────────────────────

registerTool(
	'git_deploy_keys_list',
	'List deploy keys for a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/keys`, pageQuery({ page, limit }))),
);

registerTool(
	'git_deploy_key_create',
	'Add a deploy key to a repository',
	{
		...OwnerRepo,
		title: z.string().describe('Key title'),
		key: z.string().describe('SSH public key content'),
		read_only: z.boolean().optional().describe('Read-only access (default: true)'),
		...ConnectionParam,
	},
	async ({ owner, repo, title, key, read_only, connection }) => {
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/keys`, {
			title,
			key,
			read_only: read_only ?? true,
		}));
	},
);

registerTool(
	'git_deploy_key_delete',
	'Remove a deploy key from a repository',
	{
		...OwnerRepo,
		id: z.number().describe('Deploy key ID'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/keys/${enc(id)}`)),
);

// ── Branch Protection ───────────────────────────────────────────────────

registerTool(
	'git_branch_protections_list',
	'List branch protection rules for a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/branch_protections`)),
);

registerTool(
	'git_branch_protection_create',
	'Create a branch protection rule',
	{
		...OwnerRepo,
		branch_name: z.string().describe('Branch name or pattern (e.g. "main", "release/*")'),
		enable_push: z.boolean().optional().describe('Allow push (default: true)'),
		enable_push_whitelist: z.boolean().optional().describe('Enable push whitelist'),
		push_whitelist_usernames: z.array(z.string()).optional().describe('Users allowed to push'),
		push_whitelist_actions_user: z.boolean().optional().describe('Allow the Actions user to push'),
		enable_force_push: z.boolean().optional().describe('Allow force pushes to matching branches'),
		enable_force_push_allowlist: z.boolean().optional().describe('Restrict force pushes to an allowlist'),
		force_push_allowlist_usernames: z.array(z.string()).optional().describe('Usernames allowed to force push'),
		force_push_allowlist_teams: z.array(z.string()).optional().describe('Teams allowed to force push'),
		force_push_allowlist_actions_user: z.boolean().optional().describe('Allow the Actions user to force push'),
		require_signed_commits: z.boolean().optional().describe('Require signed commits'),
		required_approvals: z.number().optional().describe('Required PR approvals (0 = none)'),
		enable_status_check: z.boolean().optional().describe('Require status checks'),
		status_check_contexts: z.array(z.string()).optional().describe('Required status check names'),
		...ConnectionParam,
	},
	async ({ owner, repo, branch_name, enable_push, enable_push_whitelist, push_whitelist_usernames, push_whitelist_actions_user, enable_force_push, enable_force_push_allowlist, force_push_allowlist_usernames, force_push_allowlist_teams, force_push_allowlist_actions_user, require_signed_commits, required_approvals, enable_status_check, status_check_contexts, connection }) => {
		const body: Record<string, unknown> = { branch_name };
		if (enable_push !== undefined) body.enable_push = enable_push;
		if (enable_push_whitelist !== undefined) body.enable_push_whitelist = enable_push_whitelist;
		if (push_whitelist_usernames) body.push_whitelist_usernames = push_whitelist_usernames;
		if (push_whitelist_actions_user !== undefined) body.push_whitelist_actions_user = push_whitelist_actions_user;
		if (enable_force_push !== undefined) body.enable_force_push = enable_force_push;
		if (enable_force_push_allowlist !== undefined) body.enable_force_push_allowlist = enable_force_push_allowlist;
		if (force_push_allowlist_usernames) body.force_push_allowlist_usernames = force_push_allowlist_usernames;
		if (force_push_allowlist_teams) body.force_push_allowlist_teams = force_push_allowlist_teams;
		if (force_push_allowlist_actions_user !== undefined) body.force_push_allowlist_actions_user = force_push_allowlist_actions_user;
		if (require_signed_commits !== undefined) body.require_signed_commits = require_signed_commits;
		if (required_approvals !== undefined) body.required_approvals = required_approvals;
		if (enable_status_check !== undefined) body.enable_status_check = enable_status_check;
		if (status_check_contexts) body.status_check_contexts = status_check_contexts;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/branch_protections`, body));
	},
);

registerTool(
	'git_branch_protection_delete',
	'Delete a branch protection rule',
	{
		...OwnerRepo,
		name: z.string().describe('Branch protection rule name'),
		...ConnectionParam,
	},
	async ({ owner, repo, name, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/branch_protections/${enc(name)}`)),
);

// ── Organization Labels ─────────────────────────────────────────────────

registerTool(
	'git_org_labels_list',
	'List labels for an organization (shared across repos - includes id, name, color, description for type/priority/status discovery)',
	{
		org: z.string().describe('Organization name'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/labels`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_label_create',
	'Create an organization-level label',
	{
		org: z.string().describe('Organization name'),
		name: z.string().describe('Label name'),
		color: z.string().describe('Color hex (e.g. "#d73a4a")'),
		description: z.string().optional().describe('Label description'),
		...ConnectionParam,
	},
	async ({ org, name, color, description, connection }) => {
		const body: Record<string, unknown> = { name, color };
		if (description) body.description = description;
		return formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/labels`, body));
	},
);

// ── Repository Secrets (Actions) ────────────────────────────────────────

registerTool(
	'git_repo_actions_secrets_list',
	'List Actions secrets for a repository (names only, values hidden)',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/secrets`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_actions_secret_create',
	'Create or update an Actions secret',
	{
		...OwnerRepo,
		name: z.string().describe('Secret name'),
		data: z.string().describe('Secret value'),
		...ConnectionParam,
	},
	async ({ owner, repo, name, data, connection }) => formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/actions/secrets/${enc(name)}`, { data })),
);

registerTool(
	'git_repo_actions_secret_delete',
	'Delete an Actions secret',
	{
		...OwnerRepo,
		name: z.string().describe('Secret name'),
		...ConnectionParam,
	},
	async ({ owner, repo, name, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/actions/secrets/${enc(name)}`)),
);

// ── Repo Transfer / Mirror ──────────────────────────────────────────────

registerTool(
	'git_repo_mirror_sync',
	'Trigger a push mirror sync for a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/mirror-sync`, {})),
);

registerTool(
	'git_repo_mirrors_list',
	'List push mirrors for a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/push_mirrors`)),
);

registerTool(
	'git_repo_mirror_create',
	'Create a push mirror to GitHub (backup). Sets up automatic push mirroring from Git to a GitHub repo.',
	{
		...OwnerRepo,
		github_owner: z.string().optional().describe('GitHub org or user (defaults to config github.org)'),
		github_repo: z.string().optional().describe('GitHub repo name (defaults to same as Git repo)'),
		github_token: z.string().optional().describe('GitHub token (defaults to config github.token)'),
		interval: z.string().optional().describe('Sync interval (e.g. "8h0m0s", default "8h0m0s")'),
		...ConnectionParam,
	},
	async ({ owner, repo, github_owner, github_repo, github_token, interval, connection }) => {
		const ghToken = github_token ?? config.github?.token;
		const ghOwner = github_owner ?? config.github?.org;
		if (!ghToken) return { content: [{ type: 'text' as const, text: 'Error: No GitHub token. Pass github_token or set github.token in config.' }] };
		if (!ghOwner) return { content: [{ type: 'text' as const, text: 'Error: No GitHub owner. Pass github_owner or set github.org in config.' }] };
		const ghRepo = github_repo ?? repo;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/push_mirrors`, {
			remote_address: `https://github.com/${ghOwner}/${ghRepo}.git`,
			remote_username: ghOwner,
			remote_password: ghToken,
			interval: interval ?? '8h0m0s',
			sync_on_commit: true,
		}));
	},
);

registerTool(
	'git_repo_mirror_delete',
	'Delete a push mirror from a repository',
	{
		...OwnerRepo,
		mirror_name: z.string().describe('Push mirror remote name (from mirrors_list)'),
		...ConnectionParam,
	},
	async ({ owner, repo, mirror_name, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/push_mirrors/${enc(mirror_name)}`)),
);

registerTool(
	'git_repo_mirror_setup_github_backup',
	'One-step GitHub backup mirror setup: creates the GitHub repo (if needed) and configures push mirror. Requires a GitHub token with repo+org scope.',
	{
		...OwnerRepo,
		github_org: z.string().optional().describe('GitHub org (defaults to config github.org)'),
		github_token: z.string().optional().describe('GitHub token (defaults to config github.token)'),
		private: z.boolean().optional().describe('Make GitHub repo private (default true)'),
		description: z.string().optional().describe('GitHub repo description'),
		interval: z.string().optional().describe('Mirror sync interval (default "8h0m0s")'),
		...ConnectionParam,
	},
	async ({ owner, repo, github_org, github_token, private: isPrivate, description, interval, connection }) => {
		const ghToken = github_token ?? config.github?.token;
		const ghOrg = github_org ?? config.github?.org;
		if (!ghToken) return { content: [{ type: 'text' as const, text: 'Error: No GitHub token. Pass github_token or set github.token in config.' }] };
		if (!ghOrg) return { content: [{ type: 'text' as const, text: 'Error: No GitHub org. Pass github_org or set github.org in config.' }] };
		const client = clientFor(connection);
		const results: string[] = [];

		// 1. Try to create the GitHub repo via GitHub API
		const ghRes = await fetch(`https://api.github.com/orgs/${enc(ghOrg)}/repos`, {
			method: 'POST',
			headers: {
				'Authorization': `Bearer ${ghToken}`,
				'Accept': 'application/vnd.github+json',
				'Content-Type': 'application/json',
			},
			body: JSON.stringify({
				name: repo,
				private: isPrivate ?? true,
				description: description ?? `Backup mirror of ${owner}/${repo} from MokoGIT`,
				auto_init: false,
				has_issues: false,
				has_wiki: false,
				has_projects: false,
			}),
		});
		const ghData = await ghRes.json();
		if (ghRes.status === 201) {
			results.push(`GitHub repo created: ${ghOrg}/${repo}`);
		} else if (ghRes.status === 422) {
			results.push(`GitHub repo already exists: ${ghOrg}/${repo}`);
		} else {
			return { content: [{ type: 'text' as const, text: `GitHub repo creation failed (${ghRes.status}): ${JSON.stringify(ghData)}` }] };
		}

		// 2. Create push mirror on Git
		const mirrorRes = await client.post(`/repos/${enc(owner)}/${enc(repo)}/push_mirrors`, {
			remote_address: `https://github.com/${ghOrg}/${repo}.git`,
			remote_username: ghOrg,
			remote_password: ghToken,
			interval: interval ?? '8h0m0s',
			sync_on_commit: true,
		});

		if (mirrorRes.status >= 400) {
			const err = mirrorRes.data as { message?: string };
			results.push(`Push mirror failed: ${err?.message ?? mirrorRes.status}`);
		} else {
			results.push(`Push mirror configured: sync every ${interval ?? '8h0m0s'}, sync on commit`);
		}

		// 3. Trigger initial sync
		await client.post(`/repos/${enc(owner)}/${enc(repo)}/mirror-sync`, {});
		results.push('Initial sync triggered');

		return { content: [{ type: 'text' as const, text: results.join('\n') }] };
	},
);

registerTool(
	'git_repo_mirror_setup_github_backup_full',
	'Full GitHub backup: mirrors code repo + wiki repo to GitHub. Creates GitHub repo, sets up push mirrors for both code and wiki, triggers initial sync.',
	{
		...OwnerRepo,
		github_org: z.string().optional().describe('GitHub org (defaults to config github.org)'),
		github_token: z.string().optional().describe('GitHub token (defaults to config github.token)'),
		private: z.boolean().optional().describe('Make GitHub repo private (default true)'),
		description: z.string().optional().describe('GitHub repo description'),
		interval: z.string().optional().describe('Mirror sync interval (default "8h0m0s")'),
		...ConnectionParam,
	},
	async ({ owner, repo, github_org, github_token, private: isPrivate, description, interval, connection }) => {
		const ghToken = github_token ?? config.github?.token;
		const ghOrg = github_org ?? config.github?.org;
		if (!ghToken) return { content: [{ type: 'text' as const, text: 'Error: No GitHub token. Pass github_token or set github.token in config.' }] };
		if (!ghOrg) return { content: [{ type: 'text' as const, text: 'Error: No GitHub org. Pass github_org or set github.org in config.' }] };
		const client = clientFor(connection);
		const syncInterval = interval ?? '8h0m0s';
		const results: string[] = [];

		// 1. Create GitHub repo (if needed)
		const ghRes = await fetch(`https://api.github.com/orgs/${enc(ghOrg)}/repos`, {
			method: 'POST',
			headers: {
				'Authorization': `Bearer ${ghToken}`,
				'Accept': 'application/vnd.github+json',
				'Content-Type': 'application/json',
			},
			body: JSON.stringify({
				name: repo,
				private: isPrivate ?? true,
				description: description ?? `Backup mirror of ${owner}/${repo} from MokoGIT`,
				auto_init: false,
				has_issues: false,
				has_wiki: true,
				has_projects: false,
			}),
		});
		const ghData = await ghRes.json();
		if (ghRes.status === 201) {
			results.push(`GitHub repo created: ${ghOrg}/${repo}`);
		} else if (ghRes.status === 422) {
			results.push(`GitHub repo already exists: ${ghOrg}/${repo}`);
		} else {
			return { content: [{ type: 'text' as const, text: `GitHub repo creation failed (${ghRes.status}): ${JSON.stringify(ghData)}` }] };
		}

		// 2. Enable wiki on GitHub repo (in case it was disabled)
		await fetch(`https://api.github.com/repos/${enc(ghOrg)}/${enc(repo)}`, {
			method: 'PATCH',
			headers: {
				'Authorization': `Bearer ${ghToken}`,
				'Accept': 'application/vnd.github+json',
				'Content-Type': 'application/json',
			},
			body: JSON.stringify({ has_wiki: true }),
		});

		// 3. Code push mirror
		const codeRes = await client.post(`/repos/${enc(owner)}/${enc(repo)}/push_mirrors`, {
			remote_address: `https://github.com/${ghOrg}/${repo}.git`,
			remote_username: ghOrg,
			remote_password: ghToken,
			interval: syncInterval,
			sync_on_commit: true,
		});
		if (codeRes.status >= 400) {
			const err = codeRes.data as { message?: string };
			results.push(`Code mirror: ${err?.message ?? `failed (${codeRes.status})`}`);
		} else {
			results.push(`Code mirror configured: sync every ${syncInterval}, sync on commit`);
		}

		// 4. Wiki push mirror - Git wiki repos are at {repo}.wiki
		// Check if wiki exists first
		const wikiCheck = await client.get(`/repos/${enc(owner)}/${enc(repo)}/wiki/pages`);
		if (wikiCheck.status < 400) {
			const wikiRes = await client.post(`/repos/${enc(owner)}/${enc(repo)}/push_mirrors`, {
				remote_address: `https://github.com/${ghOrg}/${repo}.wiki.git`,
				remote_username: ghOrg,
				remote_password: ghToken,
				interval: syncInterval,
				sync_on_commit: true,
			});
			if (wikiRes.status >= 400) {
				const err = wikiRes.data as { message?: string };
				results.push(`Wiki mirror: ${err?.message ?? `failed (${wikiRes.status})`}`);
			} else {
				results.push(`Wiki mirror configured: ${ghOrg}/${repo}.wiki.git`);
			}
		} else {
			results.push('Wiki mirror skipped: no wiki pages found');
		}

		// 5. Trigger initial sync
		await client.post(`/repos/${enc(owner)}/${enc(repo)}/mirror-sync`, {});
		results.push('Initial sync triggered');

		return { content: [{ type: 'text' as const, text: results.join('\n') }] };
	},
);

// ── Repo Statistics ─────────────────────────────────────────────────────

registerTool(
	'git_repo_languages',
	'Get language breakdown for a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/languages`)),
);

registerTool(
	'git_repo_contributors',
	'List contributors with commit counts',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/contributors`)),
);

// ── Issue Labels (Bulk) ─────────────────────────────────────────────────

registerTool(
	'git_issue_labels_set',
	'Set labels on an issue (replaces existing)',
	{
		...OwnerRepo,
		number: z.number().describe('Issue/PR number'),
		labels: z.array(z.union([z.number(), z.string()])).describe('Label IDs or names to set (use git_labels_list to discover available labels)'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, labels, connection }) => formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(number)}/labels`, { labels })),
);

// ── Diff / Compare ──────────────────────────────────────────────────────

registerTool(
	'git_compare',
	'Compare two branches, tags, or commits (returns diff stats)',
	{
		...OwnerRepo,
		base: z.string().describe('Base branch/tag/SHA.' + STRICT_REF_NOTE),
		head: z.string().describe('Head branch/tag/SHA.' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, base, head, connection }) => getWithRefGuard(connection, owner, repo, [base, head], `/repos/${enc(owner)}/${enc(repo)}/compare/${base}...${head}`),
);

// ── Git Admin (Instance-Level) ────────────────────────────────────────

registerTool(
	'git_admin_orgs_list',
	'List all organizations (admin only)',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/admin/orgs', pageQuery({ page, limit }))),
);

registerTool(
	'git_admin_users_list',
	'List all users (admin only)',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/admin/users', pageQuery({ page, limit }))),
);

registerTool(
	'git_admin_cron_list',
	'List cron tasks and their last run time (admin only)',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/admin/cron')),
);

registerTool(
	'git_admin_cron_run',
	'Trigger a cron task (admin only)',
	{
		task: z.string().describe('Cron task name (e.g. "repo_health_check", "resync_all_hooks", "repo_archive_cleanup")'),
		...ConnectionParam,
	},
	async ({ task, connection }) => formatResponse(await clientFor(connection).post(`/admin/cron/${enc(task)}`, {})),
);

// ── Generic API Call ────────────────────────────────────────────────────

registerTool(
	'git_api_request',
	'Make a raw API request to any Git v1 endpoint',
	{
		method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),
		endpoint: z.string().describe('API endpoint path (e.g. "/repos/owner/repo")'),
		body: z.record(z.string(), z.unknown()).optional().describe('Request body'),
		params: z.record(z.string(), z.string()).optional().describe('Query parameters'),
		...ConnectionParam,
	},
	async ({ method, endpoint, body, params, connection }) => {
		const client = clientFor(connection);
		switch (method) {
			case 'GET': return formatResponse(await client.get(endpoint, params));
			case 'POST': return formatResponse(await client.post(endpoint, body));
			case 'PUT': return formatResponse(await client.put(endpoint, body));
			case 'PATCH': return formatResponse(await client.patch(endpoint, body));
			case 'DELETE': return formatResponse(await client.delete(endpoint, body));
		}
	},
);

// ── Connections ──────────────────────────────────────────────────────────

registerTool(
	'git_list_connections',
	'List configured Git connections',
	{},
	async () => {
		const lines = Object.entries(config.connections).map(([name, conn]) => {
			const is_default = name === config.defaultConnection ? ' (default)' : '';
			return `  ${name}${is_default}: ${conn.baseUrl}`;
		});
		return { content: [{ type: 'text' as const, text: `Configured connections:\n${lines.join('\n')}` }] };
	},
);

// ── Metadata ────────────────────────────────────────────────────────────

registerTool(
	'git_metadata_get',
	'DEPRECATED (MokoGIT #1461): the legacy repo_metadata API is being retired. Its fields are moving to their real homes — platform to the repository record, and update_feed_format plus the extension fields to the update-stream config (git_update_stream_config_*). This GET tool still works against prod but will be removed once #1461 reaches prod. Get repo metadata (project identity, governance, distribution, build settings). Includes update_feed_format (off | joomla-xml | electron-yml), the update-server feed format for this repo; defaults are derived from the platform registry server-side.',
	{
		owner: z.string().describe('Repository owner'),
		repo: z.string().describe('Repository name'),
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) => {
		const c = clientV2For(connection);
		return formatResponse(await c.get(`/repos/${enc(owner)}/${enc(repo)}/metadata`));
	},
);

registerTool(
	'git_metadata_update',
	'DEPRECATED / BEING REMOVED (MokoGIT #1461): the repo_metadata WRITE API is already gone on the MokoGIT dev branch and will 404/405 once #1461 reaches prod. Set these values on their new homes instead — update-server settings (incl. update_feed_format) via git_update_stream_config_*; platform is now derived from the repo Makefile automatically. This tool is retained only for prod back-compat until #1461 lands there. Update repo metadata settings (partial update - only provided fields are changed). Includes update_feed_format (off | joomla-xml | electron-yml) to select the update-server feed format; optional and defaults from the platform registry server-side.',
	{
		owner: z.string().describe('Repository owner'),
		repo: z.string().describe('Repository name'),
		// identity
		// NOTE: display_name is intentionally NOT a settable param - the fork's
		// RepoMetadata model has no display_name column; it is derived server-side
		// (DerivedDisplayName() from extension_type + name), so sending it is a no-op.
		// NOTE: org is likewise NOT settable - the fork derives it from the org
		// profile (repository owner) on read (DerivedOrgName), so it is read-only
		// and sending it is a no-op. See MokoGIT-Fork issue #771.
		name: z.string().optional().describe('Project name'),
		description: z.string().optional().describe('Project description'),
		// versioning
		version_prefix: z.string().optional().describe('Tag prefix for version display (e.g. v1.26.1-moko.)'),
		// NOTE: element_name is intentionally NOT a settable param. The Joomla
		// <element> is derived at updates.xml generation time (release-asset
		// filename -> source manifest <element> -> AutoElementName), so the fork's
		// RepoMetadata model no longer stores it and the metadata API neither
		// accepts nor returns it. Sending it is a no-op. See MokoGIT-Fork PR #1047.
		// licensing
		license_spdx: z.string().optional().describe('SPDX license identifier'),
		license_name: z.string().optional().describe('Human-readable license name'),
		// governance
		platform: z.string().optional().describe('Platform (joomla, dolibarr, go, npm, mcp, generic)'),
		// TODO(#827): add npm_package/node_minimum/publish_target once the forge apiMetadata struct is confirmed to serialize them
		standards_version: z.string().optional().describe('mokocli standards version'),
		standards_source: z.string().optional().describe('URL to standards repo'),
		// distribution
		maintainer: z.string().optional().describe('Maintainer name'),
		maintainer_url: z.string().optional().describe('Maintainer website URL'),
		info_url: z.string().optional().describe('Extension info/product page URL'),
		target_version: z.string().optional().describe('Target platform version regex'),
		php_minimum: z.string().optional().describe('Minimum PHP version'),
		// update server
		update_feed_format: z
			.enum(['off', 'joomla-xml', 'electron-yml'])
			.optional()
			.describe(
				'Update-server feed format: off (no feed) | joomla-xml (Joomla updates.xml) | electron-yml (Electron latest.yml). Optional; when omitted the server defaults from the platform registry. See MokoGIT #1342/#1343.',
			),
		// build
		language: z.string().optional().describe('Primary language (Go, PHP, TypeScript)'),
		extension_type: z.string().optional().describe('Extension type (component, module, plugin, package, template, library)'),
		entry_point: z.string().optional().describe('Build entry point path'),
		// deploy
		deploy_host: z.string().optional().describe('SSH host for deploy'),
		deploy_port: z.string().optional().describe('SSH port (default 2918)'),
		deploy_user: z.string().optional().describe('SSH user'),
		deploy_path: z.string().optional().describe('Remote path for source/compose'),
		docker_image: z.string().optional().describe('Docker image name (e.g. mokoconsulting/mokogit)'),
		docker_registry: z.string().optional().describe('Docker registry host'),
		container_name: z.string().optional().describe('Docker container name'),
		health_url: z.string().optional().describe('Health check URL after deploy'),
		...ConnectionParam,
	},
	async ({ owner, repo, connection, ...fields }) => {
		// Server handles partial merge - just send the fields that were provided.
		const body: Record<string, unknown> = {};
		for (const [k, v] of Object.entries(fields)) {
			if (v !== undefined) body[k] = v;
		}
		return formatResponse(await clientV2For(connection).put(`/repos/${enc(owner)}/${enc(repo)}/metadata`, body));
	},
);

// ── Cascade Merge (rules + repo default mode) ─────────────────────────────

registerTool(
	"git_v2_get_cascade_config",
	"Get the repository's default cascade mode",
	{
		"owner": z.string(),
		"repo": z.string(),
		...ConnectionParam,
	},
		async ({ owner, repo, connection }) => {
			return formatResponse(await clientV2For(connection).get(`/repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}/cascade_config`));
		},
);

registerTool(
	"git_v2_set_cascade_config",
	"Set the repository's default cascade mode (off | notify | auto_merge | auto_resolve)",
	{
		"owner": z.string(),
		"repo": z.string(),
		body: z.record(z.string(), z.unknown()).optional().describe("Request body (JSON object matching the API schema)"),
		...ConnectionParam,
	},
		async ({ owner, repo, body, connection }) => {
			return formatResponse(await clientV2For(connection).put(`/repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}/cascade_config`, body ?? {}));
		},
);

registerTool(
	"git_v2_list_cascade_rules",
	"List cascade merge rules for a repository",
	{
		"owner": z.string(),
		"repo": z.string(),
		...ConnectionParam,
	},
		async ({ owner, repo, connection }) => {
			return formatResponse(await clientV2For(connection).get(`/repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}/cascade_rules`));
		},
);

registerTool(
	"git_v2_create_cascade_rule",
	"Create a cascade merge rule",
	{
		"owner": z.string(),
		"repo": z.string(),
		source_branch: z.string().optional().describe("Upstream branch the rule cascades FROM (e.g. stable)."),
		target_branch: z.string().optional().describe("Downstream branch the rule cascades INTO (e.g. dev)."),
		enabled: z.boolean().optional().describe("Whether the rule is active."),
		mode: z.enum(['notify', 'auto_merge', 'auto_resolve']).optional().describe("Cascade mode: notify | auto_merge | auto_resolve."),
		auto_merge: z.boolean().optional().describe("Auto-merge the generated cascade PR when it is conflict-free."),
		body: z.record(z.string(), z.unknown()).optional().describe("Extra request body fields (JSON object matching the API schema). The explicit fields above are merged over this and take precedence."),
		...ConnectionParam,
	},
		async ({ owner, repo, source_branch, target_branch, enabled, mode, auto_merge, body, connection }) => {
			const payload: Record<string, unknown> = { ...(body ?? {}) };
			if (source_branch !== undefined) payload.source_branch = source_branch;
			if (target_branch !== undefined) payload.target_branch = target_branch;
			if (enabled !== undefined) payload.enabled = enabled;
			if (mode !== undefined) payload.mode = mode;
			if (auto_merge !== undefined) payload.auto_merge = auto_merge;
			return formatResponse(await clientV2For(connection).post(`/repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}/cascade_rules`, payload));
		},
);

registerTool(
	"git_v2_get_cascade_rule",
	"Get a cascade merge rule",
	{
		"owner": z.string(),
		"repo": z.string(),
		"id": z.number(),
		...ConnectionParam,
	},
		async ({ owner, repo, id, connection }) => {
			return formatResponse(await clientV2For(connection).get(`/repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}/cascade_rules/${encodeURIComponent(String(id))}`));
		},
);

registerTool(
	"git_v2_edit_cascade_rule",
	"Edit a cascade merge rule",
	{
		"owner": z.string(),
		"repo": z.string(),
		"id": z.number(),
		source_branch: z.string().optional().describe("Upstream branch the rule cascades FROM (e.g. stable)."),
		target_branch: z.string().optional().describe("Downstream branch the rule cascades INTO (e.g. dev)."),
		enabled: z.boolean().optional().describe("Whether the rule is active."),
		mode: z.enum(['notify', 'auto_merge', 'auto_resolve']).optional().describe("Cascade mode: notify | auto_merge | auto_resolve."),
		auto_merge: z.boolean().optional().describe("Auto-merge the generated cascade PR when it is conflict-free."),
		body: z.record(z.string(), z.unknown()).optional().describe("Extra request body fields (JSON object matching the API schema). The explicit fields above are merged over this and take precedence."),
		...ConnectionParam,
	},
		async ({ owner, repo, id, source_branch, target_branch, enabled, mode, auto_merge, body, connection }) => {
			const payload: Record<string, unknown> = { ...(body ?? {}) };
			if (source_branch !== undefined) payload.source_branch = source_branch;
			if (target_branch !== undefined) payload.target_branch = target_branch;
			if (enabled !== undefined) payload.enabled = enabled;
			if (mode !== undefined) payload.mode = mode;
			if (auto_merge !== undefined) payload.auto_merge = auto_merge;
			return formatResponse(await clientV2For(connection).patch(`/repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}/cascade_rules/${encodeURIComponent(String(id))}`, payload));
		},
);

registerTool(
	"git_v2_delete_cascade_rule",
	"Delete a cascade merge rule",
	{
		"owner": z.string(),
		"repo": z.string(),
		"id": z.number(),
		body: z.record(z.string(), z.unknown()).optional().describe("Request body (JSON object matching the API schema)"),
		...ConnectionParam,
	},
		async ({ owner, repo, id, body, connection }) => {
			return formatResponse(await clientV2For(connection).delete(`/repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}/cascade_rules/${encodeURIComponent(String(id))}`, body));
		},
);

// ── Platform registry ─────────────────────────────────────────────────────

registerTool(
	'git_platforms_list',
	'List the MokoGIT platform registry (GET /api/v2/platforms): structured capabilities per platform (key, label, aliases, family, artifact, update_generator, feed_format, template_repo, manifest_based, publish_target, detect_globs).',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientV2For(connection).get('/platforms')),
);

// ── Milestones (edit / get / delete) ──────────────────────────────────────

registerTool(
	'git_milestone_get',
	'Get a single milestone',
	{ ...OwnerRepo, id: z.number().describe('Milestone ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/milestones/${enc(id)}`)),
);

registerTool(
	'git_milestone_edit',
	'Edit a milestone',
	{
		...OwnerRepo,
		id: z.number().describe('Milestone ID'),
		title: z.string().optional().describe('Milestone title'),
		description: z.string().optional().describe('Description'),
		state: z.enum(['open', 'closed']).optional().describe('State'),
		due_on: z.string().optional().describe('Due date (ISO 8601)'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, title, description, state, due_on, connection }) => {
		const body: Record<string, unknown> = {};
		if (title !== undefined) body.title = title;
		if (description !== undefined) body.description = description;
		if (state) body.state = state;
		if (due_on) body.due_on = due_on;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/milestones/${enc(id)}`, body));
	},
);

registerTool(
	'git_milestone_delete',
	'Delete a milestone',
	{ ...OwnerRepo, id: z.number().describe('Milestone ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/milestones/${enc(id)}`)),
);

// ── Labels (edit / get / delete) ──────────────────────────────────────

registerTool(
	'git_label_get',
	'Get a single repository label by id',
	{ ...OwnerRepo, id: z.number().describe('Label id'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/labels/${enc(id)}`)),
);

registerTool(
	'git_label_edit',
	'Edit a repository label',
	{
		...OwnerRepo,
		id: z.number().describe('Label id'),
		name: z.string().optional().describe('New label name'),
		color: z.string().optional().describe('New color hex (e.g. "#d73a4a")'),
		description: z.string().optional().describe('New label description'),
		exclusive: z.boolean().optional().describe('Whether the label is exclusive within its scope'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, name, color, description, exclusive, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body.name = name;
		if (color !== undefined) body.color = color;
		if (description !== undefined) body.description = description;
		if (exclusive !== undefined) body.exclusive = exclusive;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/labels/${enc(id)}`, body));
	},
);

registerTool(
	'git_label_delete',
	'Delete a repository label',
	{ ...OwnerRepo, id: z.number().describe('Label id'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/labels/${enc(id)}`)),
);

registerTool(
	'git_issue_labels_clear',
	'Remove all labels from an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number (index)'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/labels`)),
);

registerTool(
	'git_org_label_get',
	'Get a single organization-level label by id',
	{ org: z.string().describe('Organization name'), id: z.number().describe('Label id'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/labels/${enc(id)}`)),
);

registerTool(
	'git_org_label_edit',
	'Edit an organization-level label',
	{
		org: z.string().describe('Organization name'),
		id: z.number().describe('Label id'),
		name: z.string().optional().describe('New label name'),
		color: z.string().optional().describe('New color hex (e.g. "#d73a4a")'),
		description: z.string().optional().describe('New label description'),
		exclusive: z.boolean().optional().describe('Whether the label is exclusive within its scope'),
		...ConnectionParam,
	},
	async ({ org, id, name, color, description, exclusive, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body.name = name;
		if (color !== undefined) body.color = color;
		if (description !== undefined) body.description = description;
		if (exclusive !== undefined) body.exclusive = exclusive;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}/labels/${enc(id)}`, body));
	},
);

registerTool(
	'git_org_label_delete',
	'Delete an organization-level label',
	{ org: z.string().describe('Organization name'), id: z.number().describe('Label id'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/labels/${enc(id)}`)),
);

// ── Issue & Comment Reactions ──────────────────────────────────────

registerTool(
	'git_issue_reactions_list',
	'List reactions on an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/reactions`)),
);

registerTool(
	'git_issue_reaction_add',
	'Add a reaction to an issue',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number'),
		content: z.string().describe('Reaction (e.g. "+1", "-1", "laugh", "heart", "rocket", "eyes")'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, content, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/reactions`, { content })),
);

registerTool(
	'git_issue_reaction_remove',
	'Remove a reaction from an issue',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number'),
		content: z.string().describe('Reaction to remove (e.g. "+1", "-1", "laugh", "heart", "rocket", "eyes")'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, content, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/reactions`, { content })),
);

registerTool(
	'git_comment_reactions_list',
	'List reactions on an issue comment',
	{ ...OwnerRepo, id: z.number().describe('Comment ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/reactions`)),
);

registerTool(
	'git_comment_reaction_add',
	'Add a reaction to an issue comment',
	{
		...OwnerRepo,
		id: z.number().describe('Comment ID'),
		content: z.string().describe('Reaction (e.g. "+1", "-1", "laugh", "heart", "rocket", "eyes")'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, content, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/reactions`, { content })),
);

registerTool(
	'git_comment_reaction_remove',
	'Remove a reaction from an issue comment',
	{
		...OwnerRepo,
		id: z.number().describe('Comment ID'),
		content: z.string().describe('Reaction to remove (e.g. "+1", "-1", "laugh", "heart", "rocket", "eyes")'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, content, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/reactions`, { content })),
);

// ── Commit Statuses ──────────────────────────────────────

registerTool(
	'git_status_create',
	'Create a commit status (CI status) for a commit SHA',
	{
		...OwnerRepo,
		sha: z.string().describe('Commit SHA to attach the status to'),
		state: z.enum(['pending', 'success', 'error', 'failure', 'warning']).describe('Status state'),
		target_url: z.string().optional().describe('URL to associate with the status (e.g. CI run link)'),
		description: z.string().optional().describe('Short description of the status'),
		context: z.string().optional().describe('Context label to differentiate statuses (e.g. "ci/build")'),
		...ConnectionParam,
	},
	async ({ owner, repo, sha, state, target_url, description, context, connection }) => {
		const body: Record<string, unknown> = { state };
		if (target_url) body.target_url = target_url;
		if (description) body.description = description;
		if (context) body.context = context;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/statuses/${enc(sha)}`, body));
	},
);

registerTool(
	'git_statuses_list',
	'List commit statuses for a specific commit SHA',
	{ ...OwnerRepo, sha: z.string().describe('Commit SHA'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, sha, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/statuses/${enc(sha)}`, pageQuery({ page, limit }))),
);

registerTool(
	'git_ref_statuses_list',
	'List commit statuses for a git ref (branch, tag, or commit SHA)',
	{ ...OwnerRepo, ref: z.string().describe('Git ref (branch name, tag, or commit SHA).' + STRICT_REF_NOTE), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, ref, page, limit, connection }) => getWithRefGuard(connection, owner, repo, [ref], `/repos/${enc(owner)}/${enc(repo)}/commits/${enc(ref)}/statuses`, pageQuery({ page, limit })),
);

registerTool(
	'git_status_combined_get',
	'Get the combined (rolled-up) commit status for a git ref',
	{ ...OwnerRepo, ref: z.string().describe('Git ref (branch name, tag, or commit SHA).' + STRICT_REF_NOTE), ...ConnectionParam },
	async ({ owner, repo, ref, connection }) => getWithRefGuard(connection, owner, repo, [ref], `/repos/${enc(owner)}/${enc(repo)}/commits/${enc(ref)}/status`),
);

// ── Pull Request Reviews ──────────────────────────────────────

registerTool(
	'git_pull_reviews_list',
	'List all reviews on a pull request',
	{ ...OwnerRepo, index: z.number().describe('Pull request number'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, index, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/reviews`, pageQuery({ page, limit }))),
);

registerTool(
	'git_pull_review_get',
	'Get a single review on a pull request',
	{ ...OwnerRepo, index: z.number().describe('Pull request number'), id: z.number().describe('Review ID'), ...ConnectionParam },
	async ({ owner, repo, index, id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/reviews/${enc(id)}`)),
);

registerTool(
	'git_pull_review_comments_list',
	'List the line/file comments attached to a pull request review',
	{ ...OwnerRepo, index: z.number().describe('Pull request number'), id: z.number().describe('Review ID'), ...ConnectionParam },
	async ({ owner, repo, index, id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/reviews/${enc(id)}/comments`)),
);

registerTool(
	'git_pull_review_delete',
	'Delete a pull request review',
	{ ...OwnerRepo, index: z.number().describe('Pull request number'), id: z.number().describe('Review ID'), ...ConnectionParam },
	async ({ owner, repo, index, id, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/reviews/${enc(id)}`)),
);

registerTool(
	'git_pull_review_dismiss',
	'Dismiss a pull request review',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		id: z.number().describe('Review ID'),
		message: z.string().optional().describe('Reason the review is being dismissed'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, id, message, connection }) => {
		const body: Record<string, unknown> = {};
		if (message !== undefined) body.message = message;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/reviews/${enc(id)}/dismissals`, body));
	},
);

registerTool(
	'git_pull_review_undismiss',
	'Cancel the dismissal of a pull request review (restore it)',
	{ ...OwnerRepo, index: z.number().describe('Pull request number'), id: z.number().describe('Review ID'), ...ConnectionParam },
	async ({ owner, repo, index, id, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/reviews/${enc(id)}/undismissals`)),
);

registerTool(
	'git_pull_review_submit',
	'Submit a pending pull request review',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		id: z.number().describe('Review ID'),
		event: z.enum(['APPROVE', 'REQUEST_CHANGES', 'COMMENT', 'PENDING']).describe('Review action to submit'),
		body: z.string().optional().describe('Review summary comment (markdown)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, id, event, body: reviewBody, connection }) => {
		const body: Record<string, unknown> = { event };
		if (reviewBody !== undefined) body.body = reviewBody;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/reviews/${enc(id)}`, body));
	},
);

registerTool(
	'git_pull_review_requests_add',
	'Request reviews on a pull request from users and/or teams',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		reviewers: z.array(z.string()).describe('Usernames to request review from'),
		team_reviewers: z.array(z.string()).optional().describe('Team names to request review from (org repos)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, reviewers, team_reviewers, connection }) => {
		const body: Record<string, unknown> = { reviewers };
		if (team_reviewers !== undefined) body.team_reviewers = team_reviewers;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/requested_reviewers`, body));
	},
);

registerTool(
	'git_pull_review_requests_remove',
	'Cancel review requests on a pull request for users and/or teams',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		reviewers: z.array(z.string()).describe('Usernames whose review requests to cancel'),
		team_reviewers: z.array(z.string()).optional().describe('Team names whose review requests to cancel (org repos)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, reviewers, team_reviewers, connection }) => {
		const body: Record<string, unknown> = { reviewers };
		if (team_reviewers !== undefined) body.team_reviewers = team_reviewers;
		return formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/requested_reviewers`, body));
	},
);

registerTool(
	'git_pull_reviewers_list',
	'List users who can be requested to review pull requests in a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/reviewers`)),
);

// ── Repository Starring & Watching ──────────────────────────────────────

registerTool(
	'git_repo_stargazers_list',
	'List users who have starred a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/stargazers`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_subscribers_list',
	'List users watching (subscribed to) a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/subscribers`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_star',
	'Star a repository as the authenticated user',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).put(`/user/starred/${enc(owner)}/${enc(repo)}`, {})),
);

registerTool(
	'git_repo_unstar',
	'Unstar a repository as the authenticated user',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).delete(`/user/starred/${enc(owner)}/${enc(repo)}`)),
);

registerTool(
	'git_repo_star_check',
	'Check whether the authenticated user has starred a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/user/starred/${enc(owner)}/${enc(repo)}`)),
);

registerTool(
	'git_repo_watch',
	'Watch (subscribe to) a repository as the authenticated user',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/subscription`, {})),
);

registerTool(
	'git_repo_unwatch',
	'Unwatch (unsubscribe from) a repository as the authenticated user',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/subscription`)),
);

registerTool(
	'git_repo_watch_check',
	'Check the authenticated user\'s watch (subscription) status for a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/subscription`)),
);

registerTool(
	'git_user_starred_list',
	'List repositories starred by a given user',
	{ username: z.string().describe('Username'), ...PaginationParams, ...ConnectionParam },
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/starred`, pageQuery({ page, limit }))),
);

registerTool(
	'git_my_starred_list',
	'List repositories starred by the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/starred', pageQuery({ page, limit }))),
);

registerTool(
	'git_user_subscriptions_list',
	'List repositories watched (subscribed to) by a given user',
	{ username: z.string().describe('Username'), ...PaginationParams, ...ConnectionParam },
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/subscriptions`, pageQuery({ page, limit }))),
);

registerTool(
	'git_my_subscriptions_list',
	'List repositories watched (subscribed to) by the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/subscriptions', pageQuery({ page, limit }))),
);

// ── Issue & Comment Attachments ──────────────────────────────────────

registerTool(
	'git_issue_attachments_list',
	'List attachments (assets) on an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/assets`)),
);

registerTool(
	'git_issue_attachment_create',
	'Upload a file as an issue attachment (provide base64-encoded content)',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number'),
		name: z.string().describe('Attachment filename'),
		content_base64: z.string().describe('Base64-encoded file content'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, name, content_base64, connection }) => {
		const conn = getConnection(config, connection);
		const buf = Buffer.from(content_base64, 'base64');
		const res = await uploadBinary(conn, `/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/assets`, { name }, buf);
		return formatResponse(res);
	},
);

registerTool(
	'git_issue_attachment_get',
	'Get a single issue attachment',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), attachment_id: z.number().describe('Attachment ID'), ...ConnectionParam },
	async ({ owner, repo, index, attachment_id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/assets/${enc(attachment_id)}`)),
);

registerTool(
	'git_issue_attachment_edit',
	'Edit an issue attachment (rename)',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number'),
		attachment_id: z.number().describe('Attachment ID'),
		name: z.string().optional().describe('New attachment filename'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, attachment_id, name, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body['name'] = name;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/assets/${enc(attachment_id)}`, body));
	},
);

registerTool(
	'git_issue_attachment_delete',
	'Delete an issue attachment',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), attachment_id: z.number().describe('Attachment ID'), ...ConnectionParam },
	async ({ owner, repo, index, attachment_id, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/assets/${enc(attachment_id)}`)),
);

registerTool(
	'git_comment_attachments_list',
	'List attachments (assets) on an issue comment',
	{ ...OwnerRepo, id: z.number().describe('Comment ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/assets`)),
);

registerTool(
	'git_comment_attachment_create',
	'Upload a file as an issue comment attachment (provide base64-encoded content)',
	{
		...OwnerRepo,
		id: z.number().describe('Comment ID'),
		name: z.string().describe('Attachment filename'),
		content_base64: z.string().describe('Base64-encoded file content'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, name, content_base64, connection }) => {
		const conn = getConnection(config, connection);
		const buf = Buffer.from(content_base64, 'base64');
		const res = await uploadBinary(conn, `/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/assets`, { name }, buf);
		return formatResponse(res);
	},
);

registerTool(
	'git_comment_attachment_get',
	'Get a single issue comment attachment',
	{ ...OwnerRepo, id: z.number().describe('Comment ID'), attachment_id: z.number().describe('Attachment ID'), ...ConnectionParam },
	async ({ owner, repo, id, attachment_id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/assets/${enc(attachment_id)}`)),
);

registerTool(
	'git_comment_attachment_edit',
	'Edit an issue comment attachment (rename)',
	{
		...OwnerRepo,
		id: z.number().describe('Comment ID'),
		attachment_id: z.number().describe('Attachment ID'),
		name: z.string().optional().describe('New attachment filename'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, attachment_id, name, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body['name'] = name;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/assets/${enc(attachment_id)}`, body));
	},
);

registerTool(
	'git_comment_attachment_delete',
	'Delete an issue comment attachment',
	{ ...OwnerRepo, id: z.number().describe('Comment ID'), attachment_id: z.number().describe('Attachment ID'), ...ConnectionParam },
	async ({ owner, repo, id, attachment_id, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}/assets/${enc(attachment_id)}`)),
);

// ── Issue Dependencies & Blocking ──────────────────────────────────────

registerTool(
	'git_issue_dependencies_list',
	'List issues that a given issue depends on (its dependencies)',
	{ ...OwnerRepo, index: z.number().describe('Issue number (index)'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, index, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/dependencies`, pageQuery({ page, limit }))),
);

registerTool(
	'git_issue_dependency_add',
	'Add a dependency to an issue (the issue depends on the referenced issue)',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number (index) that gains the dependency'),
		dep_index: z.number().describe('Issue number (index) of the dependency to add'),
		dep_owner: z.string().optional().describe('Owner of the dependency issue (defaults to the same repository owner)'),
		dep_repo: z.string().optional().describe('Repository name of the dependency issue (defaults to the same repository)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, dep_index, dep_owner, dep_repo, connection }) => {
		const body: Record<string, unknown> = {
			index: dep_index,
			owner: dep_owner ?? owner,
			name: dep_repo ?? repo,
		};
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/dependencies`, body));
	},
);

registerTool(
	'git_issue_dependency_remove',
	'Remove a dependency from an issue',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number (index) that loses the dependency'),
		dep_index: z.number().describe('Issue number (index) of the dependency to remove'),
		dep_owner: z.string().optional().describe('Owner of the dependency issue (defaults to the same repository owner)'),
		dep_repo: z.string().optional().describe('Repository name of the dependency issue (defaults to the same repository)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, dep_index, dep_owner, dep_repo, connection }) => {
		const body: Record<string, unknown> = {
			index: dep_index,
			owner: dep_owner ?? owner,
			name: dep_repo ?? repo,
		};
		return formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/dependencies`, body));
	},
);

registerTool(
	'git_issue_blocks_list',
	'List issues that a given issue blocks',
	{ ...OwnerRepo, index: z.number().describe('Issue number (index)'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, index, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/blocks`, pageQuery({ page, limit }))),
);

registerTool(
	'git_issue_blocking_add',
	'Mark an issue as blocking another issue',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number (index) that does the blocking'),
		dep_index: z.number().describe('Issue number (index) of the issue being blocked'),
		dep_owner: z.string().optional().describe('Owner of the blocked issue (defaults to the same repository owner)'),
		dep_repo: z.string().optional().describe('Repository name of the blocked issue (defaults to the same repository)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, dep_index, dep_owner, dep_repo, connection }) => {
		const body: Record<string, unknown> = {
			index: dep_index,
			owner: dep_owner ?? owner,
			name: dep_repo ?? repo,
		};
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/blocks`, body));
	},
);

registerTool(
	'git_issue_blocking_remove',
	'Remove a blocking relationship (the issue no longer blocks the referenced issue)',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number (index) that does the blocking'),
		dep_index: z.number().describe('Issue number (index) of the issue to unblock'),
		dep_owner: z.string().optional().describe('Owner of the blocked issue (defaults to the same repository owner)'),
		dep_repo: z.string().optional().describe('Repository name of the blocked issue (defaults to the same repository)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, dep_index, dep_owner, dep_repo, connection }) => {
		const body: Record<string, unknown> = {
			index: dep_index,
			owner: dep_owner ?? owner,
			name: dep_repo ?? repo,
		};
		return formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/blocks`, body));
	},
);

// ── Issue Time Tracking & Stopwatches ──────────────────────────────────────

registerTool(
	'git_issue_time_add',
	'Add tracked time to an issue',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number'),
		time: z.number().describe('Time to add, in seconds'),
		created: z.string().optional().describe('Timestamp the time was tracked (ISO 8601)'),
		user_name: z.string().optional().describe('Username to attribute the time to (admin only)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, time, created, user_name, connection }) => {
		const body: Record<string, unknown> = { time };
		if (created) body.created = created;
		if (user_name) body.user_name = user_name;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/times`, body));
	},
);

registerTool(
	'git_issue_times_list',
	'List tracked times on an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, index, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/times`, pageQuery({ page, limit }))),
);

registerTool(
	'git_issue_time_delete',
	'Delete a specific tracked time entry on an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), id: z.number().describe('Time entry ID'), ...ConnectionParam },
	async ({ owner, repo, index, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/times/${enc(id)}`)),
);

registerTool(
	'git_issue_time_reset',
	'Reset (delete all) tracked time on an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/times`)),
);

registerTool(
	'git_repo_times_list',
	'List tracked times across all issues in a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/times`, pageQuery({ page, limit }))),
);

registerTool(
	'git_user_times_list',
	'List tracked times for a specific user across all issues in a repository',
	{ ...OwnerRepo, user: z.string().describe('Username to list tracked times for'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, user, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/times/${enc(user)}`, pageQuery({ page, limit }))),
);

registerTool(
	'git_my_times_list',
	'List tracked times for the authenticated user across all repositories',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/times', pageQuery({ page, limit }))),
);

registerTool(
	'git_issue_stopwatch_start',
	'Start a stopwatch on an issue for the authenticated user',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/stopwatch/start`, {})),
);

registerTool(
	'git_issue_stopwatch_stop',
	'Stop the running stopwatch on an issue for the authenticated user',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/stopwatch/stop`, {})),
);

registerTool(
	'git_issue_stopwatch_delete',
	'Delete (cancel) the stopwatch on an issue for the authenticated user',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/stopwatch/delete`)),
);

registerTool(
	'git_my_stopwatches_list',
	'List the authenticated user\'s active stopwatches',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/stopwatches', pageQuery({ page, limit }))),
);

// ── Issue Subscriptions ──────────────────────────────────────

registerTool(
	'git_issue_subscribe',
	'Subscribe a user to an issue (add to watchers)',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), user: z.string().describe('Username to subscribe'), ...ConnectionParam },
	async ({ owner, repo, index, user, connection }) => formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/subscriptions/${enc(user)}`, {})),
);

registerTool(
	'git_issue_unsubscribe',
	'Unsubscribe a user from an issue (remove from watchers)',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), user: z.string().describe('Username to unsubscribe'), ...ConnectionParam },
	async ({ owner, repo, index, user, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/subscriptions/${enc(user)}`)),
);

registerTool(
	'git_issue_subscription_check',
	'Check whether the authenticated user is subscribed to an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/subscriptions/check`)),
);

registerTool(
	'git_issue_subscribers_list',
	'List users subscribed to (watching) an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, index, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/subscriptions`, pageQuery({ page, limit }))),
);

// ── Issue & PR Pinning ──────────────────────────────────────

registerTool(
	'git_issue_pin',
	'Pin an issue to the repository',
	{ ...OwnerRepo, index: z.number().describe('Issue number (index)'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/pin`, {})),
);

registerTool(
	'git_issue_unpin',
	'Unpin an issue from the repository',
	{ ...OwnerRepo, index: z.number().describe('Issue number (index)'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/pin`)),
);

registerTool(
	'git_issue_pin_move',
	'Move a pinned issue to a new position',
	{ ...OwnerRepo, index: z.number().describe('Issue number (index)'), position: z.number().describe('New pin position (1-based)'), ...ConnectionParam },
	async ({ owner, repo, index, position, connection }) => formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/pin/${position}`, {})),
);

registerTool(
	'git_pinned_issues_list',
	'List a repository\'s pinned issues',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/pinned`)),
);

registerTool(
	'git_pinned_pulls_list',
	'List a repository\'s pinned pull requests',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/pinned`)),
);

registerTool(
	'git_new_pin_allowed',
	'Check whether a new issue or pull request pin is allowed in the repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/new_pin_allowed`)),
);

// ── Issue Lock / Unlock ──────────────────────────────────────

registerTool(
	'git_issue_lock',
	'Lock an issue, optionally with a reason, to prevent further comments',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number (index)'),
		reason: z.string().optional().describe('Active lock reason (e.g. "off-topic", "too heated", "resolved", "spam")'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, reason, connection }) => {
		const body: Record<string, unknown> = {};
		if (reason !== undefined) body.active_lock_reason = reason;
		return formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/lock`, body));
	},
);

registerTool(
	'git_issue_unlock',
	'Unlock a previously locked issue to allow comments again',
	{ ...OwnerRepo, index: z.number().describe('Issue number (index)'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/lock`)),
);

// ── Issue Delete & Comment Operations ──────────────────────────────────────

registerTool(
	'git_issue_delete',
	'Delete an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...ConnectionParam },
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}`)),
);

registerTool(
	'git_issue_comment_get',
	'Get a single issue comment by its comment ID',
	{ ...OwnerRepo, id: z.number().describe('Comment ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}`)),
);

registerTool(
	'git_issue_comment_edit',
	'Edit an issue comment by its comment ID',
	{ ...OwnerRepo, id: z.number().describe('Comment ID'), body: z.string().describe('New comment body (markdown)'), ...ConnectionParam },
	async ({ owner, repo, id, body: commentBody, connection }) => {
		const body: Record<string, unknown> = {};
		if (commentBody !== undefined) body.body = commentBody;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}`, body));
	},
);

registerTool(
	'git_issue_comment_delete',
	'Delete an issue comment by its comment ID',
	{ ...OwnerRepo, id: z.number().describe('Comment ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/issues/comments/${enc(id)}`)),
);

registerTool(
	'git_repo_comments_list',
	'List all issue and pull request comments in a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/comments`, pageQuery({ page, limit }))),
);

registerTool(
	'git_issue_timeline_list',
	'List all comments and timeline events for an issue',
	{ ...OwnerRepo, index: z.number().describe('Issue number'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, index, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/timeline`, pageQuery({ page, limit }))),
);

// ── Actions Workflows ──────────────────────────────────────

registerTool(
	'git_workflows_list',
	'List repository Actions workflows',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/workflows`)),
);

registerTool(
	'git_workflow_get',
	'Get a specific Actions workflow',
	{ ...OwnerRepo, workflow_id: z.string().describe('Workflow ID or filename (e.g. pre-release.yml)'), ...ConnectionParam },
	async ({ owner, repo, workflow_id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/workflows/${enc(workflow_id)}`)),
);

registerTool(
	'git_workflow_enable',
	'Enable an Actions workflow',
	{ ...OwnerRepo, workflow_id: z.string().describe('Workflow ID or filename (e.g. pre-release.yml)'), ...ConnectionParam },
	async ({ owner, repo, workflow_id, connection }) =>
		formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/actions/workflows/${enc(workflow_id)}/enable`, {})),
);

registerTool(
	'git_workflow_disable',
	'Disable an Actions workflow',
	{ ...OwnerRepo, workflow_id: z.string().describe('Workflow ID or filename (e.g. pre-release.yml)'), ...ConnectionParam },
	async ({ owner, repo, workflow_id, connection }) =>
		formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/actions/workflows/${enc(workflow_id)}/disable`, {})),
);

// ── Actions Run Management ──────────────────────────────────────

registerTool(
	'git_actions_run_rerun',
	'Re-run all jobs of a workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), ...ConnectionParam },
	async ({ owner, repo, run_id, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}/rerun`, {})),
);

registerTool(
	'git_actions_run_rerun_failed',
	'Re-run only the failed jobs of a workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), ...ConnectionParam },
	async ({ owner, repo, run_id, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}/rerun-failed-jobs`, {})),
);

registerTool(
	'git_actions_job_rerun',
	'Re-run a single job of a workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), job_id: z.number().describe('Job ID'), ...ConnectionParam },
	async ({ owner, repo, run_id, job_id, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}/jobs/${enc(job_id)}/rerun`, {})),
);

registerTool(
	'git_actions_run_delete',
	'Delete a workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), ...ConnectionParam },
	async ({ owner, repo, run_id, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}`)),
);

registerTool(
	'git_actions_run_attempt_get',
	'Get a specific attempt of a workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), attempt: z.number().describe('Attempt number'), ...ConnectionParam },
	async ({ owner, repo, run_id, attempt, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}/attempts/${attempt}`)),
);

registerTool(
	'git_actions_run_attempt_jobs_list',
	'List jobs for a specific attempt of a workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), attempt: z.number().describe('Attempt number'), ...ConnectionParam },
	async ({ owner, repo, run_id, attempt, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}/attempts/${attempt}/jobs`)),
);

registerTool(
	'git_actions_tasks_list',
	'List action tasks for a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/tasks`, pageQuery({ page, limit }))),
);

// ── Actions Artifacts ──────────────────────────────────────

registerTool(
	'git_artifacts_list',
	'List Actions artifacts for a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/artifacts`, pageQuery({ page, limit }))),
);

registerTool(
	'git_artifacts_of_run_list',
	'List Actions artifacts produced by a specific workflow run',
	{ ...OwnerRepo, run_id: z.number().describe('Run ID'), ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, run_id, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runs/${enc(run_id)}/artifacts`, pageQuery({ page, limit }))),
);

registerTool(
	'git_artifact_get',
	'Get a single Actions artifact by ID',
	{ ...OwnerRepo, artifact_id: z.number().describe('Artifact ID'), ...ConnectionParam },
	async ({ owner, repo, artifact_id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/artifacts/${enc(artifact_id)}`)),
);

registerTool(
	'git_artifact_download',
	'Download an Actions artifact as a zip (returns the download response)',
	{ ...OwnerRepo, artifact_id: z.number().describe('Artifact ID'), ...ConnectionParam },
	async ({ owner, repo, artifact_id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/artifacts/${enc(artifact_id)}/zip`)),
);

registerTool(
	'git_artifact_delete',
	'Delete an Actions artifact',
	{ ...OwnerRepo, artifact_id: z.number().describe('Artifact ID'), ...ConnectionParam },
	async ({ owner, repo, artifact_id, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/actions/artifacts/${enc(artifact_id)}`)),
);

// ── Actions Runners ──────────────────────────────────────

registerTool(
	'git_repo_runners_list',
	'List Actions runners registered to a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runners`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_runner_get',
	'Get a specific Actions runner for a repository',
	{ ...OwnerRepo, runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ owner, repo, runner_id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_repo_runner_delete',
	'Delete an Actions runner from a repository',
	{ ...OwnerRepo, runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ owner, repo, runner_id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_repo_runner_registration_token',
	'Get a registration token for adding an Actions runner to a repository',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/runners/registration-token`)),
);

registerTool(
	'git_org_runners_list',
	'List Actions runners registered to an organization',
	{ org: z.string().describe('Organization name'), ...PaginationParams, ...ConnectionParam },
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/actions/runners`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_runner_get',
	'Get a specific Actions runner for an organization',
	{ org: z.string().describe('Organization name'), runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ org, runner_id, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_org_runner_delete',
	'Delete an Actions runner from an organization',
	{ org: z.string().describe('Organization name'), runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ org, runner_id, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_org_runner_registration_token',
	'Get a registration token for adding an Actions runner to an organization',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/actions/runners/registration-token`)),
);

registerTool(
	'git_user_runners_list',
	'List Actions runners registered to the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/actions/runners', pageQuery({ page, limit }))),
);

registerTool(
	'git_user_runner_get',
	'Get a specific Actions runner for the authenticated user',
	{ runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ runner_id, connection }) => formatResponse(await clientFor(connection).get(`/user/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_user_runner_delete',
	'Delete an Actions runner from the authenticated user',
	{ runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ runner_id, connection }) => formatResponse(await clientFor(connection).delete(`/user/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_user_runner_registration_token',
	'Get a registration token for adding an Actions runner to the authenticated user',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/user/actions/runners/registration-token')),
);

registerTool(
	'git_admin_runners_list',
	'List all Actions runners registered to the instance (admin)',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/admin/actions/runners', pageQuery({ page, limit }))),
);

registerTool(
	'git_admin_runner_get',
	'Get a specific instance-level Actions runner (admin)',
	{ runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ runner_id, connection }) => formatResponse(await clientFor(connection).get(`/admin/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_admin_runner_delete',
	'Delete an instance-level Actions runner (admin)',
	{ runner_id: z.number().describe('Runner ID'), ...ConnectionParam },
	async ({ runner_id, connection }) => formatResponse(await clientFor(connection).delete(`/admin/actions/runners/${enc(runner_id)}`)),
);

registerTool(
	'git_admin_runner_registration_token',
	'Get a registration token for adding an instance-level Actions runner (admin)',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/admin/actions/runners/registration-token')),
);

// ── Actions Runner Maintenance (drain) ─────────────────────
// Toggle a runner's maintenance/drain mode: when enabled the runner finishes
// its current job, then stops accepting new tasks; disabling resumes it.
// Mirrors each scope's get/delete runner resource path with `/maintenance`
// appended, via POST (MokoGIT API, see MokoEnterprises/MokoGIT#2109).

registerTool(
	'git_admin_runner_set_maintenance',
	'Toggle maintenance/drain mode for an instance-level Actions runner (admin): finish the current job, then stop accepting new tasks (maintenance=true); maintenance=false resumes the runner',
	{ runner_id: z.number().describe('Runner ID'), maintenance: z.boolean().describe('true to enter maintenance/drain mode, false to resume accepting tasks'), ...ConnectionParam },
	async ({ runner_id, maintenance, connection }) => formatResponse(await clientFor(connection).post(`/admin/actions/runners/${enc(runner_id)}/maintenance`, { maintenance })),
);

registerTool(
	'git_org_runner_set_maintenance',
	'Toggle maintenance/drain mode for an organization Actions runner: finish the current job, then stop accepting new tasks (maintenance=true); maintenance=false resumes the runner',
	{ org: z.string().describe('Organization name'), runner_id: z.number().describe('Runner ID'), maintenance: z.boolean().describe('true to enter maintenance/drain mode, false to resume accepting tasks'), ...ConnectionParam },
	async ({ org, runner_id, maintenance, connection }) => formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/actions/runners/${enc(runner_id)}/maintenance`, { maintenance })),
);

registerTool(
	'git_repo_runner_set_maintenance',
	'Toggle maintenance/drain mode for a repository Actions runner: finish the current job, then stop accepting new tasks (maintenance=true); maintenance=false resumes the runner',
	{ ...OwnerRepo, runner_id: z.number().describe('Runner ID'), maintenance: z.boolean().describe('true to enter maintenance/drain mode, false to resume accepting tasks'), ...ConnectionParam },
	async ({ owner, repo, runner_id, maintenance, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/actions/runners/${enc(runner_id)}/maintenance`, { maintenance })),
);

registerTool(
	'git_user_runner_set_maintenance',
	'Toggle maintenance/drain mode for an Actions runner of the authenticated user: finish the current job, then stop accepting new tasks (maintenance=true); maintenance=false resumes the runner',
	{ runner_id: z.number().describe('Runner ID'), maintenance: z.boolean().describe('true to enter maintenance/drain mode, false to resume accepting tasks'), ...ConnectionParam },
	async ({ runner_id, maintenance, connection }) => formatResponse(await clientFor(connection).post(`/user/actions/runners/${enc(runner_id)}/maintenance`, { maintenance })),
);

// ── Actions Variables ──────────────────────────────────────

registerTool(
	'git_repo_variables_list',
	'List Actions variables for a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/variables`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_variable_get',
	'Get an Actions variable for a repository',
	{ ...OwnerRepo, variable_name: z.string().describe('Variable name'), ...ConnectionParam },
	async ({ owner, repo, variable_name, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/actions/variables/${enc(variable_name)}`)),
);

registerTool(
	'git_repo_variable_create',
	'Create an Actions variable for a repository',
	{ ...OwnerRepo, variable_name: z.string().describe('Variable name'), value: z.string().describe('Variable value'), ...ConnectionParam },
	async ({ owner, repo, variable_name, value, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/actions/variables/${enc(variable_name)}`, { value })),
);

registerTool(
	'git_repo_variable_update',
	'Update an Actions variable for a repository',
	{ ...OwnerRepo, variable_name: z.string().describe('Variable name'), value: z.string().describe('New variable value'), ...ConnectionParam },
	async ({ owner, repo, variable_name, value, connection }) => formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/actions/variables/${enc(variable_name)}`, { value })),
);

registerTool(
	'git_repo_variable_delete',
	'Delete an Actions variable for a repository',
	{ ...OwnerRepo, variable_name: z.string().describe('Variable name'), ...ConnectionParam },
	async ({ owner, repo, variable_name, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/actions/variables/${enc(variable_name)}`)),
);

registerTool(
	'git_org_variables_list',
	'List Actions variables for an organization',
	{ org: z.string().describe('Organization name'), ...PaginationParams, ...ConnectionParam },
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/actions/variables`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_variable_get',
	'Get an Actions variable for an organization',
	{ org: z.string().describe('Organization name'), variable_name: z.string().describe('Variable name'), ...ConnectionParam },
	async ({ org, variable_name, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/actions/variables/${enc(variable_name)}`)),
);

registerTool(
	'git_org_variable_create',
	'Create an Actions variable for an organization',
	{ org: z.string().describe('Organization name'), variable_name: z.string().describe('Variable name'), value: z.string().describe('Variable value'), ...ConnectionParam },
	async ({ org, variable_name, value, connection }) => formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/actions/variables/${enc(variable_name)}`, { value })),
);

registerTool(
	'git_org_variable_update',
	'Update an Actions variable for an organization',
	{ org: z.string().describe('Organization name'), variable_name: z.string().describe('Variable name'), value: z.string().describe('New variable value'), ...ConnectionParam },
	async ({ org, variable_name, value, connection }) => formatResponse(await clientFor(connection).put(`/orgs/${enc(org)}/actions/variables/${enc(variable_name)}`, { value })),
);

registerTool(
	'git_org_variable_delete',
	'Delete an Actions variable for an organization',
	{ org: z.string().describe('Organization name'), variable_name: z.string().describe('Variable name'), ...ConnectionParam },
	async ({ org, variable_name, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/actions/variables/${enc(variable_name)}`)),
);

registerTool(
	'git_user_variables_list',
	'List Actions variables for the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/actions/variables', pageQuery({ page, limit }))),
);

registerTool(
	'git_user_variable_get',
	'Get an Actions variable for the authenticated user',
	{ variable_name: z.string().describe('Variable name'), ...ConnectionParam },
	async ({ variable_name, connection }) => formatResponse(await clientFor(connection).get(`/user/actions/variables/${enc(variable_name)}`)),
);

registerTool(
	'git_user_variable_create',
	'Create an Actions variable for the authenticated user',
	{ variable_name: z.string().describe('Variable name'), value: z.string().describe('Variable value'), ...ConnectionParam },
	async ({ variable_name, value, connection }) => formatResponse(await clientFor(connection).post(`/user/actions/variables/${enc(variable_name)}`, { value })),
);

registerTool(
	'git_user_variable_update',
	'Update an Actions variable for the authenticated user',
	{ variable_name: z.string().describe('Variable name'), value: z.string().describe('New variable value'), ...ConnectionParam },
	async ({ variable_name, value, connection }) => formatResponse(await clientFor(connection).put(`/user/actions/variables/${enc(variable_name)}`, { value })),
);

registerTool(
	'git_user_variable_delete',
	'Delete an Actions variable for the authenticated user',
	{ variable_name: z.string().describe('Variable name'), ...ConnectionParam },
	async ({ variable_name, connection }) => formatResponse(await clientFor(connection).delete(`/user/actions/variables/${enc(variable_name)}`)),
);

// ── Actions Secrets (org & user) ──────────────────────────────────────

registerTool(
	'git_org_secrets_list',
	'List Actions secrets for an organization (names only, values hidden)',
	{ org: z.string().describe('Organization name'), ...PaginationParams, ...ConnectionParam },
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/actions/secrets`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_secret_create',
	'Create or update an organization Actions secret',
	{ org: z.string().describe('Organization name'), secret_name: z.string().describe('Secret name'), data: z.string().describe('Secret value'), ...ConnectionParam },
	async ({ org, secret_name, data, connection }) => formatResponse(await clientFor(connection).put(`/orgs/${enc(org)}/actions/secrets/${enc(secret_name)}`, { data })),
);

registerTool(
	'git_org_secret_delete',
	'Delete an organization Actions secret',
	{ org: z.string().describe('Organization name'), secret_name: z.string().describe('Secret name'), ...ConnectionParam },
	async ({ org, secret_name, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/actions/secrets/${enc(secret_name)}`)),
);

registerTool(
	'git_user_secret_create',
	'Create or update a user Actions secret for the authenticated user',
	{ secret_name: z.string().describe('Secret name'), data: z.string().describe('Secret value'), ...ConnectionParam },
	async ({ secret_name, data, connection }) => formatResponse(await clientFor(connection).put(`/user/actions/secrets/${enc(secret_name)}`, { data })),
);

registerTool(
	'git_user_secret_delete',
	'Delete a user Actions secret for the authenticated user',
	{ secret_name: z.string().describe('Secret name'), ...ConnectionParam },
	async ({ secret_name, connection }) => formatResponse(await clientFor(connection).delete(`/user/actions/secrets/${enc(secret_name)}`)),
);

// ── User Following ──────────────────────────────────────

registerTool(
	'git_my_followers_list',
	'List followers of the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/followers', pageQuery({ page, limit }))),
);

registerTool(
	'git_my_following_list',
	'List users the authenticated user is following',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/following', pageQuery({ page, limit }))),
);

registerTool(
	'git_my_following_check',
	'Check whether the authenticated user follows the given user',
	{ username: z.string().describe('Username to check for following'), ...ConnectionParam },
	async ({ username, connection }) => formatResponse(await clientFor(connection).get(`/user/following/${enc(username)}`)),
);

registerTool(
	'git_user_follow',
	'Follow a user (as the authenticated user)',
	{ username: z.string().describe('Username to follow'), ...ConnectionParam },
	async ({ username, connection }) => formatResponse(await clientFor(connection).put(`/user/following/${enc(username)}`, {})),
);

registerTool(
	'git_user_unfollow',
	'Unfollow a user (as the authenticated user)',
	{ username: z.string().describe('Username to unfollow'), ...ConnectionParam },
	async ({ username, connection }) => formatResponse(await clientFor(connection).delete(`/user/following/${enc(username)}`)),
);

registerTool(
	'git_user_followers_list',
	'List followers of a given user',
	{ username: z.string().describe('Username whose followers to list'), ...PaginationParams, ...ConnectionParam },
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/followers`, pageQuery({ page, limit }))),
);

registerTool(
	'git_user_following_list',
	'List users that a given user is following',
	{ username: z.string().describe('Username whose following list to retrieve'), ...PaginationParams, ...ConnectionParam },
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/following`, pageQuery({ page, limit }))),
);

registerTool(
	'git_user_following_check',
	'Check whether a given user follows a target user',
	{ username: z.string().describe('Username to check (the potential follower)'), target: z.string().describe('Target username being followed'), ...ConnectionParam },
	async ({ username, target, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/following/${target}`)),
);

// ── User & Org Blocking ──────────────────────────────────────

registerTool(
	'git_my_blocked_list',
	'List users the authenticated user has blocked',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/list_blocked', pageQuery({ page, limit }))),
);

registerTool(
	'git_user_block',
	'Block a user as the authenticated user',
	{ username: z.string().describe('Username of the user to block'), ...ConnectionParam },
	async ({ username, connection }) => formatResponse(await clientFor(connection).put(`/user/blocks/${enc(username)}`, {})),
);

registerTool(
	'git_user_unblock',
	'Unblock a user as the authenticated user',
	{ username: z.string().describe('Username of the user to unblock'), ...ConnectionParam },
	async ({ username, connection }) => formatResponse(await clientFor(connection).delete(`/user/blocks/${enc(username)}`)),
);

registerTool(
	'git_user_block_check',
	'Check whether the authenticated user has blocked a given user',
	{ username: z.string().describe('Username to check for a block'), ...ConnectionParam },
	async ({ username, connection }) => formatResponse(await clientFor(connection).get(`/user/blocks/${enc(username)}`)),
);

registerTool(
	'git_org_blocked_list',
	'List users blocked by an organization',
	{ org: z.string().describe('Organization name'), ...PaginationParams, ...ConnectionParam },
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/blocks`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_block',
	'Block a user on behalf of an organization',
	{ org: z.string().describe('Organization name'), username: z.string().describe('Username of the user to block'), ...ConnectionParam },
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).put(`/orgs/${enc(org)}/blocks/${enc(username)}`, {})),
);

registerTool(
	'git_org_unblock',
	'Unblock a user on behalf of an organization',
	{ org: z.string().describe('Organization name'), username: z.string().describe('Username of the user to unblock'), ...ConnectionParam },
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/blocks/${enc(username)}`)),
);

registerTool(
	'git_org_block_check',
	'Check whether an organization has blocked a given user',
	{ org: z.string().describe('Organization name'), username: z.string().describe('Username to check for a block'), ...ConnectionParam },
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/blocks/${enc(username)}`)),
);

// ── User GPG Keys ──────────────────────────────────────

registerTool(
	'git_my_gpg_keys_list',
	'List the authenticated user\'s GPG keys',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/gpg_keys', pageQuery({ page, limit }))),
);

registerTool(
	'git_my_gpg_key_get',
	'Get a GPG key owned by the authenticated user',
	{ id: z.number().describe('GPG key ID'), ...ConnectionParam },
	async ({ id, connection }) => formatResponse(await clientFor(connection).get(`/user/gpg_keys/${enc(id)}`)),
);

registerTool(
	'git_my_gpg_key_create',
	'Add a GPG key for the authenticated user',
	{
		armored_public_key: z.string().describe('ASCII-armored GPG public key'),
		signature: z.string().optional().describe('Armored signature proving key ownership'),
		...ConnectionParam,
	},
	async ({ armored_public_key, signature, connection }) => {
		const body: Record<string, unknown> = { armored_public_key };
		if (signature !== undefined) body.signature = signature;
		return formatResponse(await clientFor(connection).post('/user/gpg_keys', body));
	},
);

registerTool(
	'git_my_gpg_key_delete',
	'Delete a GPG key owned by the authenticated user',
	{ id: z.number().describe('GPG key ID'), ...ConnectionParam },
	async ({ id, connection }) => formatResponse(await clientFor(connection).delete(`/user/gpg_keys/${enc(id)}`)),
);

registerTool(
	'git_my_gpg_key_token',
	'Get a verification token used to prove ownership of a GPG key',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/user/gpg_key_token')),
);

registerTool(
	'git_my_gpg_key_verify',
	'Verify a GPG key by submitting the signed verification token',
	{
		key_id: z.string().describe('GPG key ID to verify'),
		signature: z.string().describe('Armored signature of the verification token'),
		...ConnectionParam,
	},
	async ({ key_id, signature, connection }) =>
		formatResponse(await clientFor(connection).post('/user/gpg_key_verify', { key_id, signature })),
);

registerTool(
	'git_user_gpg_keys_list',
	'List the GPG keys for a given user (public)',
	{ username: z.string().describe('Username whose GPG keys to list'), ...PaginationParams, ...ConnectionParam },
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/gpg_keys`, pageQuery({ page, limit }))),
);

// ── User SSH Keys ──────────────────────────────────────

registerTool(
	'git_my_ssh_keys_list',
	'List SSH keys for the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/keys', pageQuery({ page, limit }))),
);

registerTool(
	'git_my_ssh_key_get',
	'Get an SSH key of the authenticated user by ID',
	{ id: z.number().describe('SSH key ID'), ...ConnectionParam },
	async ({ id, connection }) => formatResponse(await clientFor(connection).get(`/user/keys/${enc(id)}`)),
);

registerTool(
	'git_my_ssh_key_create',
	'Add an SSH key to the authenticated user',
	{
		title: z.string().describe('Key title'),
		key: z.string().describe('SSH public key content'),
		read_only: z.boolean().optional().describe('Read-only access (default: true)'),
		...ConnectionParam,
	},
	async ({ title, key, read_only, connection }) =>
		formatResponse(await clientFor(connection).post('/user/keys', { title, key, read_only: read_only ?? true })),
);

registerTool(
	'git_my_ssh_key_delete',
	'Delete an SSH key of the authenticated user by ID',
	{ id: z.number().describe('SSH key ID'), ...ConnectionParam },
	async ({ id, connection }) => formatResponse(await clientFor(connection).delete(`/user/keys/${enc(id)}`)),
);

registerTool(
	'git_user_ssh_keys_list',
	'List the public SSH keys of a user by username',
	{ username: z.string().describe('Username whose public keys to list'), ...PaginationParams, ...ConnectionParam },
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/keys`, pageQuery({ page, limit }))),
);

// ── User Access Tokens & OAuth2 Apps ──────────────────────────────────────

registerTool(
	'git_user_tokens_list',
	'List access tokens for a user',
	{ username: z.string().describe('Owner of the tokens (username in the path)'), ...PaginationParams, ...ConnectionParam },
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/tokens`, pageQuery({ page, limit }))),
);

registerTool(
	'git_user_token_create',
	'Create an access token for a user',
	{
		username: z.string().describe('Owner of the token (username in the path)'),
		name: z.string().describe('Name of the token'),
		scopes: z.array(z.string()).optional().describe('Token scopes (e.g. ["read:user", "write:repository"])'),
		all_repos: z.boolean().optional().describe('Token covers all repos incl. future (default true)'),
		repo_ids: z.array(z.number()).optional().describe('When all_repos=false, restrict to these repository IDs'),
		repos: z.array(z.string()).optional().describe('Convenience: repo full-names (owner/name) resolved to IDs client-side'),
		...ConnectionParam,
	},
	async ({ username, name, scopes, all_repos, repo_ids, repos, connection }) => {
		const client = clientFor(connection);
		const body: Record<string, unknown> = { name };
		if (scopes) body.scopes = scopes;
		if (all_repos !== undefined) body.all_repos = all_repos;
		// Resolve any repo full-names (owner/name) to numeric IDs and merge with
		// any explicit repo_ids. The forge expects the field name `repo_ids`.
		const resolvedIds: number[] = Array.isArray(repo_ids) ? [...repo_ids] : [];
		if (repos?.length) {
			for (const full of repos) {
				const slash = full.indexOf('/');
				if (slash < 0) throw new Error(`repos entries must be "owner/name": got "${full}"`);
				const ownerPart = full.slice(0, slash);
				const repoPart = full.slice(slash + 1);
				const res = await client.get(`/repos/${enc(ownerPart)}/${enc(repoPart)}`);
				const id = (res.data as { id?: number } | null)?.id;
				if (typeof id !== 'number') throw new Error(`Could not resolve repository id for "${full}" (status ${res.status})`);
				resolvedIds.push(id);
			}
		}
		if (resolvedIds.length) body.repo_ids = resolvedIds;
		return formatResponse(await client.post(`/users/${enc(username)}/tokens`, body));
	},
);

registerTool(
	'git_user_token_delete',
	'Delete an access token for a user',
	{ username: z.string().describe('Owner of the token (username in the path)'), token: z.string().describe('Token id or name to delete'), ...ConnectionParam },
	async ({ username, token, connection }) => formatResponse(await clientFor(connection).delete(`/users/${enc(username)}/tokens/${token}`)),
);

// Resolve a token id-or-name to its numeric id for the edit/rotate endpoints,
// whose server routes key on the numeric {id} (unlike delete, which accepts a
// name in-path). A purely-numeric `token` is used as-is; otherwise we list the
// user's tokens and match by name (unique, exact) — mirroring how the create
// tool resolves repo full-names client-side. Errors on an unknown or ambiguous
// name with the available names rather than guessing.
async function resolveTokenId(client: GitClient, username: string, token: string): Promise<number> {
	if (/^\d+$/.test(token)) return Number(token);
	const res = await client.get(`/users/${enc(username)}/tokens`, pageQuery({ limit: 50 }));
	if (res.status >= 400) {
		throw new Error(`Could not list tokens for "${username}" to resolve name "${token}" (status ${res.status})`);
	}
	const list = Array.isArray(res.data) ? (res.data as Array<{ id?: number; name?: string }>) : [];
	const matches = list.filter((t) => t.name === token);
	if (matches.length === 0) {
		const names = list.map((t) => t.name).filter(Boolean).join(', ');
		throw new Error(`No token named "${token}" for user "${username}"${names ? ` (available: ${names})` : ''}`);
	}
	if (matches.length > 1) {
		throw new Error(`Token name "${token}" is ambiguous for user "${username}" (${matches.length} matches); pass the numeric id instead`);
	}
	const id = matches[0].id;
	if (typeof id !== 'number') throw new Error(`Resolved token "${token}" has no numeric id`);
	return id;
}

registerTool(
	'git_user_token_edit',
	'Edit an access token for a user (scopes/name/repo-scoping) in place',
	{
		username: z.string().describe('Owner of the token (username in the path)'),
		token: z.string().describe('Token id or name to edit (a name is resolved to its id via the tokens list)'),
		scopes: z.array(z.string()).optional().describe('Replacement token scopes (e.g. ["read:user", "write:repository"])'),
		name: z.string().optional().describe('New name for the token'),
		all_repos: z.boolean().optional().describe('Token covers all repos incl. future'),
		repo_ids: z.array(z.number()).optional().describe('When all_repos=false, restrict to these repository IDs'),
		repos: z.array(z.string()).optional().describe('Convenience: repo full-names (owner/name) resolved to IDs client-side'),
		...ConnectionParam,
	},
	async ({ username, token, scopes, name, all_repos, repo_ids, repos, connection }) => {
		const client = clientFor(connection);
		const id = await resolveTokenId(client, username, token);
		// Include only the fields the caller provided (EditAccessTokenOption).
		const body: Record<string, unknown> = {};
		if (name !== undefined) body.name = name;
		if (scopes) body.scopes = scopes;
		if (all_repos !== undefined) body.all_repos = all_repos;
		const resolvedIds: number[] = Array.isArray(repo_ids) ? [...repo_ids] : [];
		if (repos?.length) {
			for (const full of repos) {
				const slash = full.indexOf('/');
				if (slash < 0) throw new Error(`repos entries must be "owner/name": got "${full}"`);
				const ownerPart = full.slice(0, slash);
				const repoPart = full.slice(slash + 1);
				const r = await client.get(`/repos/${enc(ownerPart)}/${enc(repoPart)}`);
				const rid = (r.data as { id?: number } | null)?.id;
				if (typeof rid !== 'number') throw new Error(`Could not resolve repository id for "${full}" (status ${r.status})`);
				resolvedIds.push(rid);
			}
		}
		if (resolvedIds.length) body.repo_ids = resolvedIds;
		return formatResponse(await client.patch(`/users/${enc(username)}/tokens/${enc(id)}`, body));
	},
);

registerTool(
	'git_user_token_rotate',
	'Rotate an access token for a user — regenerate the secret, keeping id/name/scopes. Returns the new secret (sha1).',
	{
		username: z.string().describe('Owner of the token (username in the path)'),
		token: z.string().describe('Token id or name to rotate (a name is resolved to its id via the tokens list)'),
		...ConnectionParam,
	},
	async ({ username, token, connection }) => {
		const client = clientFor(connection);
		const id = await resolveTokenId(client, username, token);
		// POST with no body; the response includes the rotated token's new `sha1`.
		return formatResponse(await client.post(`/users/${enc(username)}/tokens/${enc(id)}/rotate`));
	},
);

registerTool(
	'git_oauth2_apps_list',
	'List OAuth2 applications for the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/applications/oauth2', pageQuery({ page, limit }))),
);

registerTool(
	'git_oauth2_app_get',
	'Get an OAuth2 application for the authenticated user',
	{ id: z.number().describe('OAuth2 application id'), ...ConnectionParam },
	async ({ id, connection }) => formatResponse(await clientFor(connection).get(`/user/applications/oauth2/${enc(id)}`)),
);

registerTool(
	'git_oauth2_app_create',
	'Create an OAuth2 application for the authenticated user',
	{
		name: z.string().describe('Application name'),
		redirect_uris: z.array(z.string()).describe('Allowed redirect URIs'),
		confidential_client: z.boolean().optional().describe('Whether the client is confidential (can keep a secret)'),
		...ConnectionParam,
	},
	async ({ name, redirect_uris, confidential_client, connection }) => {
		const body: Record<string, unknown> = { name, redirect_uris };
		if (confidential_client !== undefined) body.confidential_client = confidential_client;
		return formatResponse(await clientFor(connection).post('/user/applications/oauth2', body));
	},
);

registerTool(
	'git_oauth2_app_edit',
	'Update an OAuth2 application for the authenticated user',
	{
		id: z.number().describe('OAuth2 application id'),
		name: z.string().describe('Application name'),
		redirect_uris: z.array(z.string()).describe('Allowed redirect URIs'),
		confidential_client: z.boolean().optional().describe('Whether the client is confidential (can keep a secret)'),
		...ConnectionParam,
	},
	async ({ id, name, redirect_uris, confidential_client, connection }) => {
		const body: Record<string, unknown> = { name, redirect_uris };
		if (confidential_client !== undefined) body.confidential_client = confidential_client;
		return formatResponse(await clientFor(connection).patch(`/user/applications/oauth2/${enc(id)}`, body));
	},
);

registerTool(
	'git_oauth2_app_delete',
	'Delete an OAuth2 application for the authenticated user',
	{ id: z.number().describe('OAuth2 application id'), ...ConnectionParam },
	async ({ id, connection }) => formatResponse(await clientFor(connection).delete(`/user/applications/oauth2/${enc(id)}`)),
);

// ── User Emails ──────────────────────────────────────

registerTool(
	'git_my_emails_list',
	'List the email addresses for the authenticated user',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/user/emails', pageQuery({ page, limit }))),
);

registerTool(
	'git_my_email_add',
	'Add email addresses to the authenticated user',
	{ emails: z.array(z.string()).describe('Email addresses to add to the authenticated user'), ...ConnectionParam },
	async ({ emails, connection }) => formatResponse(await clientFor(connection).post('/user/emails', { emails })),
);

registerTool(
	'git_my_email_delete',
	'Delete email addresses from the authenticated user',
	{ emails: z.array(z.string()).describe('Email addresses to delete from the authenticated user'), ...ConnectionParam },
	async ({ emails, connection }) => formatResponse(await clientFor(connection).delete('/user/emails', { emails })),
);

// ── User Settings & Avatar ──────────────────────────────────────

registerTool(
	'git_my_settings_get',
	'Get the authenticated user account settings',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/user/settings')),
);

registerTool(
	'git_my_settings_update',
	'Update the authenticated user account settings',
	{
		full_name: z.string().optional().describe('Display/full name'),
		website: z.string().optional().describe('Website URL'),
		description: z.string().optional().describe('Profile bio/description'),
		location: z.string().optional().describe('Location'),
		hide_email: z.boolean().optional().describe('Hide email address from public view'),
		hide_activity: z.boolean().optional().describe('Hide activity from public profile'),
		theme: z.string().optional().describe('UI theme name'),
		diff_view_style: z.string().optional().describe('Diff view style (e.g. "unified" or "split")'),
		...ConnectionParam,
	},
	async ({ full_name, website, description, location, hide_email, hide_activity, theme, diff_view_style, connection }) => {
		const body: Record<string, unknown> = {};
		if (full_name !== undefined) body.full_name = full_name;
		if (website !== undefined) body.website = website;
		if (description !== undefined) body.description = description;
		if (location !== undefined) body.location = location;
		if (hide_email !== undefined) body.hide_email = hide_email;
		if (hide_activity !== undefined) body.hide_activity = hide_activity;
		if (theme !== undefined) body.theme = theme;
		if (diff_view_style !== undefined) body.diff_view_style = diff_view_style;
		return formatResponse(await clientFor(connection).patch('/user/settings', body));
	},
);

registerTool(
	'git_my_avatar_update',
	'Update the authenticated user avatar',
	{ image_base64: z.string().describe('Avatar image content encoded as a base64 string'), ...ConnectionParam },
	async ({ image_base64, connection }) => formatResponse(await clientFor(connection).post('/user/avatar', { image: image_base64 })),
);

registerTool(
	'git_my_avatar_delete',
	'Delete the authenticated user avatar',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).delete('/user/avatar')),
);

// ── Packages ──────────────────────────────

registerTool(
	'git_packages_list',
	'List packages owned by a user or organization',
	{
		owner: z.string().describe('Package owner (user or org)'),
		type: z.string().optional().describe('Filter by package type (e.g. npm, container, maven, generic)'),
		q: z.string().optional().describe('Filter by package name query'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, type, q, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (type) params['type'] = type;
		if (q) params['q'] = q;
		return formatResponse(await clientFor(connection).get(`/packages/${enc(owner)}`, params));
	},
);

registerTool(
	'git_package_get',
	'Get a specific package version',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		package_version: z.string().describe('Package version'),
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, package_version, connection }) =>
		formatResponse(await clientFor(connection).get(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}/${enc(package_version)}`)),
);

registerTool(
	'git_package_version_latest',
	'Get the latest version of a package',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, connection }) =>
		formatResponse(await clientFor(connection).get(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}/-/latest`)),
);

registerTool(
	'git_package_versions_list',
	'List all versions of a package',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}`, pageQuery({ page, limit }))),
);

registerTool(
	'git_package_files_list',
	'List files for a specific package version',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		package_version: z.string().describe('Package version'),
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, package_version, connection }) =>
		formatResponse(await clientFor(connection).get(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}/${enc(package_version)}/files`)),
);

registerTool(
	'git_package_delete',
	'Delete an entire package (all versions)',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, connection }) =>
		formatResponse(await clientFor(connection).delete(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}`)),
);

registerTool(
	'git_package_version_delete',
	'Delete a specific package version',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		package_version: z.string().describe('Package version'),
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, package_version, connection }) =>
		formatResponse(await clientFor(connection).delete(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}/${enc(package_version)}`)),
);

registerTool(
	'git_package_link',
	'Link a package to a repository',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		repo_name: z.string().describe('Repository name to link the package to'),
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, repo_name, connection }) =>
		formatResponse(await clientFor(connection).post(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}/-/link/${enc(repo_name)}`, {})),
);

registerTool(
	'git_package_unlink',
	'Unlink a package from its repository',
	{
		owner: z.string().describe('Package owner (user or org)'),
		package_type: z.string().describe('Package type (e.g. npm, container, maven, generic)'),
		package_name: z.string().describe('Package name'),
		...ConnectionParam,
	},
	async ({ owner, package_type, package_name, connection }) =>
		formatResponse(await clientFor(connection).post(`/packages/${enc(owner)}/${enc(package_type)}/${enc(package_name)}/-/unlink`, {})),
);

// ── Bulk Issue Operations (Moko) ──────────────────────────────

registerTool(
	'git_issue_bulk_set_assignees',
	'Set assignees on multiple issues at once (MokoGIT bulk operation)',
	{
		...OwnerRepo,
		issue_ids: z.array(z.number()).describe('Issue numbers to update'),
		assignees: z.array(z.string()).describe('Usernames to assign to each issue'),
		...ConnectionParam,
	},
	async ({ owner, repo, issue_ids, assignees, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/bulk/assignees`, { issues: issue_ids, assignees })),
);

registerTool(
	'git_issue_bulk_set_labels',
	'Set labels on multiple issues at once (MokoGIT bulk operation)',
	{
		...OwnerRepo,
		issue_ids: z.array(z.number()).describe('Issue numbers to update'),
		labels: z.array(z.union([z.number(), z.string()])).describe('Label IDs or names to set on each issue (use git_labels_list to discover)'),
		...ConnectionParam,
	},
	async ({ owner, repo, issue_ids, labels, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/bulk/labels`, { issues: issue_ids, labels })),
);

registerTool(
	'git_issue_bulk_set_milestone',
	'Set the milestone on multiple issues at once (MokoGIT bulk operation)',
	{
		...OwnerRepo,
		issue_ids: z.array(z.number()).describe('Issue numbers to update'),
		milestone: z.number().describe('Milestone ID to set on each issue (0 to clear)'),
		...ConnectionParam,
	},
	async ({ owner, repo, issue_ids, milestone, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/bulk/milestone`, { issues: issue_ids, milestone_id: milestone })),
);

registerTool(
	'git_issue_bulk_set_state',
	'Set the state on multiple issues at once (MokoGIT bulk operation)',
	{
		...OwnerRepo,
		issue_ids: z.array(z.number()).describe('Issue numbers to update'),
		state: z.enum(['open', 'closed']).describe('State to set on each issue'),
		...ConnectionParam,
	},
	async ({ owner, repo, issue_ids, state, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/bulk/state`, { issues: issue_ids, state })),
);

// ── Issue Deadline ──────────────────────────────

registerTool(
	'git_issue_set_deadline',
	'Set or update the deadline (due date) on an issue',
	{
		...OwnerRepo,
		index: z.number().describe('Issue number'),
		due_date: z.string().describe('Deadline as an ISO 8601 date-time string (e.g. "2026-12-31T23:59:59Z")'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, due_date, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/issues/${enc(index)}/deadline`, { due_date })),
);

// ── Pull Request Advanced ──────────────────────────────

registerTool(
	'git_pull_edit',
	'Edit a pull request (title, body, state, base branch, assignees, labels, milestone)',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		title: z.string().optional().describe('New title'),
		body: z.string().optional().describe('New body (markdown)'),
		state: z.enum(['open', 'closed']).optional().describe('State'),
		base: z.string().optional().describe('New base branch'),
		assignees: z.array(z.string()).optional().describe('Usernames to assign'),
		labels: z.array(z.number()).optional().describe('Label IDs'),
		milestone: z.number().optional().describe('Milestone ID'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, title, body: prBody, state, base, assignees, labels, milestone, connection }) => {
		const body: Record<string, unknown> = {};
		if (title !== undefined) body.title = title;
		if (prBody !== undefined) body.body = prBody;
		if (state !== undefined) body.state = state;
		if (base !== undefined) body.base = base;
		if (assignees !== undefined) body.assignees = assignees;
		if (labels !== undefined) body.labels = labels;
		if (milestone !== undefined) body.milestone = milestone;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}`, body));
	},
);

registerTool(
	'git_pull_update_branch',
	'Merge the base branch into the head branch of a pull request (update the PR branch)',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		style: z.enum(['merge', 'rebase']).optional().describe('Update style (default: merge)'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, style, connection }) => {
		const body: Record<string, unknown> = {};
		if (style !== undefined) body.style = style;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/update`, body));
	},
);

registerTool(
	'git_pull_merge_upstream',
	'Merge the upstream branch into a fork/repo base branch (sync a fork)',
	{
		...OwnerRepo,
		branch: z.string().describe('Branch to sync with its upstream'),
		ff_only: z.boolean().optional().describe('Only allow fast-forward merges'),
		...ConnectionParam,
	},
	async ({ owner, repo, branch, ff_only, connection }) => {
		const body: Record<string, unknown> = { branch };
		if (ff_only !== undefined) body.ff_only = ff_only;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/merge-upstream`, body));
	},
);

registerTool(
	'git_pull_auto_merge_cancel',
	'Cancel a scheduled auto-merge for a pull request',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/merge`)),
);

registerTool(
	'git_pull_is_merged',
	'Check whether a pull request has been merged (204 = merged, 404 = not merged)',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		...ConnectionParam,
	},
	async ({ owner, repo, index, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/merge`)),
);

registerTool(
	'git_pull_commits',
	'List commits in a pull request',
	{
		...OwnerRepo,
		index: z.number().describe('Pull request number'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, index, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(index)}/commits`, pageQuery({ page, limit }))),
);

registerTool(
	'git_pull_by_base_head',
	'Get a pull request by its base and head branches',
	{
		...OwnerRepo,
		base: z.string().describe('Base branch name. STRICT REFS (#236): a bare channel name that is both a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		head: z.string().describe('Head branch name. STRICT REFS (#236): a bare channel name that is both a branch and a tag at different commits is REFUSED — qualify with refs/heads/<name> (toggle with MOKOGIT_MCP_STRICT_REFS=0).'),
		...ConnectionParam,
	},
	async ({ owner, repo, base, head, connection }) => {
		const client = clientFor(connection);
		const blocked = await assertRefsUnambiguous(client, owner, repo, [base, head]);
		if (blocked) return blocked;
		return formatResponse(await client.get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(normalizeRef(base) ?? base)}/${enc(normalizeRef(head) ?? head)}`));
	},
);

registerTool(
	'git_commit_pull',
	'Get the pull request associated with a commit SHA',
	{
		...OwnerRepo,
		sha: z.string().describe('Commit SHA'),
		...ConnectionParam,
	},
	async ({ owner, repo, sha, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/commits/${enc(sha)}/pull`)),
);

// ── Repository Migration ──────────────────────────────

registerTool(
	'git_repo_migrate',
	'Migrate an external repository into MokoGIT by cloning (or mirroring) from a remote URL',
	{
		clone_addr: z.string().describe('URL of the external repository to clone/migrate from'),
		repo_name: z.string().describe('Name for the new repository'),
		repo_owner: z.string().optional().describe('Username or org that will own the new repo (defaults to the authenticated user)'),
		uid: z.number().optional().describe('Numeric user ID of the owner (deprecated; prefer repo_owner)'),
		service: z.enum(['git', 'github', 'git', 'gitlab', 'gogs', 'onedev', 'gitbucket', 'codebase']).optional().describe('Type of the remote service being migrated from'),
		auth_username: z.string().optional().describe('Username for authenticating against the source repository'),
		auth_password: z.string().optional().describe('Password for authenticating against the source repository'),
		auth_token: z.string().optional().describe('Access token for authenticating against the source repository'),
		mirror: z.boolean().optional().describe('Keep the repository as a mirror that syncs from the source'),
		mirror_interval: z.string().optional().describe('Sync interval for mirror repos (e.g. "8h0m0s")'),
		private: z.boolean().optional().describe('Make the migrated repository private'),
		description: z.string().optional().describe('Description for the new repository'),
		wiki: z.boolean().optional().describe('Migrate the wiki'),
		issues: z.boolean().optional().describe('Migrate issues'),
		pull_requests: z.boolean().optional().describe('Migrate pull requests'),
		releases: z.boolean().optional().describe('Migrate releases'),
		milestones: z.boolean().optional().describe('Migrate milestones'),
		labels: z.boolean().optional().describe('Migrate labels'),
		lfs: z.boolean().optional().describe('Migrate Git LFS objects'),
		lfs_endpoint: z.string().optional().describe('Custom Git LFS endpoint URL'),
		...ConnectionParam,
	},
	async ({ clone_addr, repo_name, repo_owner, uid, service, auth_username, auth_password, auth_token, mirror, mirror_interval, private: priv, description, wiki, issues, pull_requests, releases, milestones, labels, lfs, lfs_endpoint, connection }) => {
		const body: Record<string, unknown> = { clone_addr, repo_name };
		if (repo_owner !== undefined) body.repo_owner = repo_owner;
		if (uid !== undefined) body.uid = uid;
		if (service !== undefined) body.service = service;
		if (auth_username !== undefined) body.auth_username = auth_username;
		if (auth_password !== undefined) body.auth_password = auth_password;
		if (auth_token !== undefined) body.auth_token = auth_token;
		if (mirror !== undefined) body.mirror = mirror;
		if (mirror_interval !== undefined) body.mirror_interval = mirror_interval;
		if (priv !== undefined) body.private = priv;
		if (description !== undefined) body.description = description;
		if (wiki !== undefined) body.wiki = wiki;
		if (issues !== undefined) body.issues = issues;
		if (pull_requests !== undefined) body.pull_requests = pull_requests;
		if (releases !== undefined) body.releases = releases;
		if (milestones !== undefined) body.milestones = milestones;
		if (labels !== undefined) body.labels = labels;
		if (lfs !== undefined) body.lfs = lfs;
		if (lfs_endpoint !== undefined) body.lfs_endpoint = lfs_endpoint;
		return formatResponse(await clientFor(connection).post(`/repos/migrate`, body));
	},
);

// ── Repository Transfer ──────────────────────────────

registerTool(
	'git_repo_transfer',
	'Transfer a repository to a new owner (user or organization)',
	{
		...OwnerRepo,
		new_owner: z.string().describe('Username or organization name to transfer the repository to'),
		team_ids: z.array(z.number()).optional().describe('Team IDs to grant access when transferring to an organization'),
		...ConnectionParam,
	},
	async ({ owner, repo, new_owner, team_ids, connection }) => {
		const body: Record<string, unknown> = { new_owner };
		if (team_ids !== undefined) body.team_ids = team_ids;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/transfer`, body));
	},
);

registerTool(
	'git_repo_transfer_accept',
	'Accept a pending repository transfer',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/transfer/accept`, {})),
);

registerTool(
	'git_repo_transfer_reject',
	'Reject a pending repository transfer',
	{ ...OwnerRepo, ...ConnectionParam },
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/transfer/reject`, {})),
);

// ── Repository Team Access ──────────────────────────────

registerTool(
	'git_repo_teams_list',
	'List teams that have access to a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/teams`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_team_check',
	'Check whether a team has access to a repository',
	{
		...OwnerRepo,
		team: z.string().describe('Team name'),
		...ConnectionParam,
	},
	async ({ owner, repo, team, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/teams/${enc(team)}`)),
);

registerTool(
	'git_repo_team_add',
	'Grant a team access to a repository',
	{
		...OwnerRepo,
		team: z.string().describe('Team name'),
		...ConnectionParam,
	},
	async ({ owner, repo, team, connection }) =>
		formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/teams/${enc(team)}`, {})),
);

registerTool(
	'git_repo_team_remove',
	'Revoke a team\'s access to a repository',
	{
		...OwnerRepo,
		team: z.string().describe('Team name'),
		...ConnectionParam,
	},
	async ({ owner, repo, team, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/teams/${enc(team)}`)),
);

// ── Repository Avatar ──────────────────────────────

registerTool(
	'git_repo_avatar_set',
	'Update the avatar image for a repository',
	{
		...OwnerRepo,
		image_base64: z.string().describe('Base64-encoded image data for the new repository avatar'),
		...ConnectionParam,
	},
	async ({ owner, repo, image_base64, connection }) =>
		formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/avatar`, { image: image_base64 })),
);

registerTool(
	'git_repo_avatar_delete',
	'Delete the avatar image for a repository',
	{
		...OwnerRepo,
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/avatar`)),
);

// ── Repository Git Hooks ──────────────────────────────

registerTool(
	'git_repo_githooks_list',
	'List the git hooks configured on a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/hooks/git`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_githook_get',
	'Get a specific git hook on a repository by its id',
	{
		...OwnerRepo,
		hook_id: z.string().describe('Git hook id (e.g. "pre-receive", "update", "post-receive")'),
		...ConnectionParam,
	},
	async ({ owner, repo, hook_id, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/hooks/git/${enc(hook_id)}`)),
);

registerTool(
	'git_repo_githook_edit',
	'Edit a git hook on a repository (set its script content and/or active state)',
	{
		...OwnerRepo,
		hook_id: z.string().describe('Git hook id (e.g. "pre-receive", "update", "post-receive")'),
		content: z.string().optional().describe('Git hook script content'),
		is_active: z.boolean().optional().describe('Whether the git hook is active'),
		...ConnectionParam,
	},
	async ({ owner, repo, hook_id, content, is_active, connection }) => {
		const body: Record<string, unknown> = {};
		if (content !== undefined) body.content = content;
		if (is_active !== undefined) body.is_active = is_active;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/hooks/git/${enc(hook_id)}`, body));
	},
);

registerTool(
	'git_repo_githook_delete',
	'Delete a git hook on a repository',
	{
		...OwnerRepo,
		hook_id: z.string().describe('Git hook id (e.g. "pre-receive", "update", "post-receive")'),
		...ConnectionParam,
	},
	async ({ owner, repo, hook_id, connection }) =>
		formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/hooks/git/${enc(hook_id)}`)),
);

// ── Repository Archive / Raw / Refs / Notes ──────────────────────────────

registerTool(
	'git_repo_archive_get',
	'Get a repository archive (zip or tar.gz) for a ref',
	{
		...OwnerRepo,
		archive: z.string().describe('Archive name including format extension (e.g. "main.zip", "v1.0.0.tar.gz")'),
		...ConnectionParam,
	},
	async ({ owner, repo, archive, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/archive/${archive}`)),
);

registerTool(
	'git_repo_raw_get',
	'Get the raw contents of a file in a repository',
	{
		...OwnerRepo,
		filepath: z.string().describe('File path (e.g. "src/index.ts")'),
		ref: z.string().optional().describe('Branch/tag/commit (default: default branch).' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, filepath, ref, connection }) => {
		const params: Record<string, string> = {};
		if (ref) params['ref'] = ref;
		return getWithRefGuard(connection, owner, repo, [ref], `/repos/${enc(owner)}/${enc(repo)}/raw/${encPath(filepath)}`, params);
	},
);

registerTool(
	'git_repo_media_get',
	'Get the raw contents of a file in a repository, resolving Git LFS pointers to the underlying media',
	{
		...OwnerRepo,
		filepath: z.string().describe('File path (e.g. "assets/logo.png")'),
		ref: z.string().optional().describe('Branch/tag/commit (default: default branch).' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, filepath, ref, connection }) => {
		const params: Record<string, string> = {};
		if (ref) params['ref'] = ref;
		return getWithRefGuard(connection, owner, repo, [ref], `/repos/${enc(owner)}/${enc(repo)}/media/${encPath(filepath)}`, params);
	},
);

registerTool(
	'git_repo_blob_get',
	'Get a git blob object by its SHA',
	{
		...OwnerRepo,
		sha: z.string().describe('Blob SHA'),
		...ConnectionParam,
	},
	// Blob SHAs are object hashes, not channel names — no ref ambiguity possible,
	// so this stays a plain GET (the #236 guard would never fire on a SHA anyway).
	async ({ owner, repo, sha, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/git/blobs/${enc(sha)}`)),
);

registerTool(
	'git_repo_refs_list',
	'List all git references (branches and tags) in a repository',
	{
		...OwnerRepo,
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/git/refs`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_ref_get',
	'Get git references matching a specific ref path (e.g. "heads/main", "tags/v1.0.0")',
	{
		...OwnerRepo,
		ref: z.string().describe('Ref path (e.g. "heads/main" or "tags/v1.0.0")'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, ref, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/git/refs/${enc(ref)}`, pageQuery({ page, limit }))),
);

registerTool(
	'git_repo_annotated_tag_get',
	'Get an annotated git tag object by its SHA',
	{
		...OwnerRepo,
		sha: z.string().describe('Annotated tag SHA'),
		...ConnectionParam,
	},
	async ({ owner, repo, sha, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/git/tags/${enc(sha)}`)),
);

registerTool(
	'git_repo_note_get',
	'Get the git note attached to a commit by its SHA',
	{
		...OwnerRepo,
		sha: z.string().describe('Commit SHA the note is attached to'),
		...ConnectionParam,
	},
	async ({ owner, repo, sha, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/git/notes/${enc(sha)}`)),
);

registerTool(
	'git_repo_editorconfig_get',
	'Get the resolved EditorConfig properties for a file path in a repository',
	{
		...OwnerRepo,
		filepath: z.string().describe('File path to resolve EditorConfig for (e.g. "src/index.ts")'),
		ref: z.string().optional().describe('Branch/tag/commit (default: default branch)'),
		...ConnectionParam,
	},
	async ({ owner, repo, filepath, ref, connection }) => {
		const params: Record<string, string> = {};
		if (ref) params['ref'] = ref;
		return formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/editorconfig/${encPath(filepath)}`, params));
	},
);

// ── Repository Diff / Patch ──────────────────────────────

registerTool(
	'git_commit_diff_download',
	'Download the diff or patch for a single commit (returns raw diff/patch text)',
	{
		...OwnerRepo,
		sha: z.string().describe('Commit SHA or ref (branch/tag/commit) to diff'),
		diff_type: z.enum(['diff', 'patch']).describe('Output format: "diff" for a unified diff, "patch" for a git-formatted patch (mailbox)'),
		...ConnectionParam,
	},
	async ({ owner, repo, sha, diff_type, connection }) => {
		const res = await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/git/commits/${enc(sha)}.${diff_type}`);
		if (res.status >= 400) return formatResponse(res);
		const text = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
		return { content: [{ type: 'text' as const, text }] };
	},
);

registerTool(
	'git_pull_diff_download',
	'Download the diff or patch for a pull request (returns raw diff/patch text)',
	{
		...OwnerRepo,
		number: z.number().describe('Pull request index/number to diff'),
		diff_type: z.enum(['diff', 'patch']).describe('Output format: "diff" for a unified diff, "patch" for a git-formatted patch (mailbox)'),
		binary: z.boolean().optional().describe('Include binary file changes in the diff/patch'),
		...ConnectionParam,
	},
	async ({ owner, repo, number, diff_type, binary, connection }) => {
		const params: Record<string, string> = {};
		if (binary !== undefined) params['binary'] = String(binary);
		const res = await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/pulls/${enc(number)}.${diff_type}`, params);
		if (res.status >= 400) return formatResponse(res);
		const text = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
		return { content: [{ type: 'text' as const, text }] };
	},
);

registerTool(
	'git_repo_diff_apply',
	'Apply a diff/patch to a repository (repoApplyDiffPatch), committing the result',
	{
		...OwnerRepo,
		content: z.string().describe('The raw diff/patch text to apply to the repository'),
		message: z.string().optional().describe('Commit message for the applied patch'),
		branch: z.string().optional().describe('Branch to apply the patch to (default: default branch)'),
		new_branch: z.string().optional().describe('Create a new branch from "branch" and commit the patch there'),
		author_name: z.string().optional().describe('Commit author name'),
		author_email: z.string().optional().describe('Commit author email'),
		committer_name: z.string().optional().describe('Commit committer name'),
		committer_email: z.string().optional().describe('Commit committer email'),
		signoff: z.boolean().optional().describe('Add a Signed-off-by trailer to the commit'),
		...ConnectionParam,
	},
	async ({ owner, repo, content, message, branch, new_branch, author_name, author_email, committer_name, committer_email, signoff, connection }) => {
		const body: Record<string, unknown> = { content };
		if (message !== undefined) body.message = message;
		if (branch !== undefined) body.branch = branch;
		if (new_branch !== undefined) body.new_branch = new_branch;
		if (author_name !== undefined || author_email !== undefined) {
			body.author = {};
			if (author_name !== undefined) (body.author as Record<string, unknown>).name = author_name;
			if (author_email !== undefined) (body.author as Record<string, unknown>).email = author_email;
		}
		if (committer_name !== undefined || committer_email !== undefined) {
			body.committer = {};
			if (committer_name !== undefined) (body.committer as Record<string, unknown>).name = committer_name;
			if (committer_email !== undefined) (body.committer as Record<string, unknown>).email = committer_email;
		}
		if (signoff !== undefined) body.signoff = signoff;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/diffpatch`, body));
	},
);

registerTool(
	'git_repo_change_files',
	'Create, update, and/or delete multiple files in a single commit (repoChangeFiles)',
	{
		...OwnerRepo,
		files: z.array(z.object({
			operation: z.enum(['create', 'update', 'delete']).describe('Operation to perform on this file'),
			path: z.string().describe('File path relative to the repository root'),
			content: z.string().optional().describe('New file content, base64-encoded (required for create/update)'),
			sha: z.string().optional().describe('Blob SHA of the file being changed (required for update/delete)'),
			from_path: z.string().optional().describe('Original path when moving/renaming a file'),
		})).describe('Array of file change operations to commit together'),
		message: z.string().optional().describe('Commit message'),
		branch: z.string().optional().describe('Branch to commit to (default: default branch).' + STRICT_REF_NOTE),
		new_branch: z.string().optional().describe('Create a new branch from "branch" and commit there'),
		author_name: z.string().optional().describe('Commit author name'),
		author_email: z.string().optional().describe('Commit author email'),
		committer_name: z.string().optional().describe('Commit committer name'),
		committer_email: z.string().optional().describe('Commit committer email'),
		signoff: z.boolean().optional().describe('Add a Signed-off-by trailer to the commit'),
		...ConnectionParam,
	},
	async ({ owner, repo, files, message, branch, new_branch, author_name, author_email, committer_name, committer_email, signoff, connection }) => {
		const client = clientFor(connection);
		const blocked = await assertRefsUnambiguous(client, owner, repo, [branch]);
		if (blocked) return blocked;
		const body: Record<string, unknown> = { files };
		if (message !== undefined) body.message = message;
		if (branch !== undefined) body.branch = normalizeRef(branch);
		if (new_branch !== undefined) body.new_branch = new_branch;
		if (author_name !== undefined || author_email !== undefined) {
			body.author = {};
			if (author_name !== undefined) (body.author as Record<string, unknown>).name = author_name;
			if (author_email !== undefined) (body.author as Record<string, unknown>).email = author_email;
		}
		if (committer_name !== undefined || committer_email !== undefined) {
			body.committer = {};
			if (committer_name !== undefined) (body.committer as Record<string, unknown>).name = committer_name;
			if (committer_email !== undefined) (body.committer as Record<string, unknown>).email = committer_email;
		}
		if (signoff !== undefined) body.signoff = signoff;
		return formatResponse(await client.post(`/repos/${enc(owner)}/${enc(repo)}/contents`, body));
	},
);

// ── Repository Contents (Advanced) & Templates ──────────────────────────────

registerTool(
	'git_contents_ext_get',
	'Get the metadata and contents of a file or directory in a repository (extended response). File bytes are inlined (content/encoding) in the same call for files up to 512 KiB (#336); a full-ref form (refs/heads/<branch> or refs/tags/<tag>) in `ref` is normalized to the bare name the endpoint expects.',
	{
		...OwnerRepo,
		filepath: z.string().describe('Path of the file or directory to get (e.g. "src/index.ts" or "src")'),
		ref: z.string().optional().describe('Name of the commit/branch/tag (default: default branch).' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, filepath, ref, connection }) => {
		const params: Record<string, string> = {};
		if (ref) params['ref'] = ref;
		return getWithRefGuard(connection, owner, repo, [ref], `/repos/${enc(owner)}/${enc(repo)}/contents-ext/${encPath(filepath)}`, params, true);
	},
);

registerTool(
	'git_contents_list',
	'Get the metadata of all the entries of the root directory of a repository',
	{
		...OwnerRepo,
		ref: z.string().optional().describe('Name of the commit/branch/tag (default: default branch).' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, ref, connection }) => {
		const params: Record<string, string> = {};
		if (ref) params['ref'] = ref;
		return getWithRefGuard(connection, owner, repo, [ref], `/repos/${enc(owner)}/${enc(repo)}/contents`, params);
	},
);

registerTool(
	'git_file_contents_get',
	'Get the contents of one or more files in a repository via query parameters (GET). File bytes are inlined (content/encoding) in the same call for files up to 512 KiB (#336); a full-ref form (refs/heads/<branch> or refs/tags/<tag>) in `ref` is normalized to the bare name the endpoint expects.',
	{
		...OwnerRepo,
		files: z.array(z.string()).optional().describe('List of file paths to fetch (repeated "files" query params)'),
		ref: z.string().optional().describe('Name of the commit/branch/tag (default: default branch).' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, files, ref, connection }) => {
		// #339: the file-contents `ref` query param wants a bare name; a
		// full-ref form (refs/heads/<b>) 400s. Normalize before building the query.
		const nref = normalizeRef(ref);
		const search = new URLSearchParams();
		if (files !== undefined) for (const f of files) search.append('files', f);
		if (nref) search.append('ref', nref);
		const qs = search.toString();
		const path = qs ? `/repos/${enc(owner)}/${enc(repo)}/file-contents?${qs}` : `/repos/${enc(owner)}/${enc(repo)}/file-contents`;
		return getWithRefGuard(connection, owner, repo, [nref], path, undefined, true);
	},
);

registerTool(
	'git_file_contents_batch_get',
	'Get the metadata and contents of a list of files in a repository via a request body (POST)',
	{
		...OwnerRepo,
		files: z.array(z.string()).describe('List of file paths to fetch the contents for'),
		ref: z.string().optional().describe('Name of the commit/branch/tag (default: default branch).' + STRICT_REF_NOTE),
		...ConnectionParam,
	},
	async ({ owner, repo, files, ref, connection }) => {
		const nref = normalizeRef(ref);
		const path = nref
			? `/repos/${enc(owner)}/${enc(repo)}/file-contents?ref=${encodeURIComponent(nref)}`
			: `/repos/${enc(owner)}/${enc(repo)}/file-contents`;
		const client = clientFor(connection);
		const res = await client.post(path, { files });
		// mokogit-mcp #336: inline null `content` file bytes (best-effort, capped).
		if (res.status < 400) await inlineFileContents(client, owner, repo, res.data);
		return formatResponse(res);
	},
);

// git_manifest_* removed — /manifest route retired in forge #754; use git_metadata_* (/metadata).

registerTool(
	'git_issue_templates_get',
	'Get the issue templates configured for a repository',
	{
		...OwnerRepo,
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issue_templates`)),
);

registerTool(
	'git_issue_config_get',
	'Get the issue config (blank_issues_enabled and contact links) of a repository',
	{
		...OwnerRepo,
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issue_config`)),
);

registerTool(
	'git_issue_config_validate',
	'Validate the issue config of a repository',
	{
		...OwnerRepo,
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/issue_config/validate`)),
);

registerTool(
	'git_repo_licenses_get',
	'Get the license(s) detected in a repository',
	{
		...OwnerRepo,
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) =>
		formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/licenses`)),
);

// ── Webhook Management (repo) ──────────────────────────────

registerTool(
	'git_webhook_get',
	'Get a single webhook for a repository by hook ID',
	{ ...OwnerRepo, hook_id: z.number().describe('Webhook ID'), ...ConnectionParam },
	async ({ owner, repo, hook_id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/hooks/${enc(hook_id)}`)),
);

registerTool(
	'git_webhook_edit',
	'Edit an existing webhook for a repository',
	{
		...OwnerRepo,
		hook_id: z.number().describe('Webhook ID'),
		config: z.record(z.string()).optional().describe('Webhook config key-value pairs (e.g. {"url": "...", "content_type": "json"})'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ owner, repo, hook_id, config, events, active, connection }) => {
		const body: Record<string, unknown> = {};
		if (config !== undefined) body.config = config;
		if (events !== undefined) body.events = events;
		if (active !== undefined) body.active = active;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/hooks/${enc(hook_id)}`, body));
	},
);

registerTool(
	'git_webhook_delete',
	'Delete a webhook from a repository',
	{ ...OwnerRepo, hook_id: z.number().describe('Webhook ID'), ...ConnectionParam },
	async ({ owner, repo, hook_id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/hooks/${enc(hook_id)}`)),
);

registerTool(
	'git_webhook_test',
	'Test a webhook by triggering a delivery for a repository',
	{ ...OwnerRepo, hook_id: z.number().describe('Webhook ID'), ...ConnectionParam },
	async ({ owner, repo, hook_id, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/hooks/${enc(hook_id)}/tests`, {})),
);

// ── Webhooks (org / user / admin) ──────────────────────────────

registerTool(
	'git_org_webhook_create',
	'Create a webhook for an organization',
	{
		org: z.string().describe('Organization name'),
		type: z.enum(['git', 'slack', 'discord', 'dingtalk', 'telegram', 'msteams', 'feishu', 'matrix', 'wechatwork', 'packagist']).describe('Hook type'),
		url: z.string().describe('Webhook URL'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ org, type, url, events, active, connection }) => {
		const body: Record<string, unknown> = {
			type,
			config: { url, content_type: 'json' },
			events: events ?? ['push'],
			active: active ?? true,
		};
		return formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/hooks`, body));
	},
);

registerTool(
	'git_org_webhook_list',
	'List webhooks for an organization',
	{
		org: z.string().describe('Organization name'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/hooks`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_webhook_get',
	'Get a single webhook for an organization',
	{
		org: z.string().describe('Organization name'),
		hook_id: z.number().describe('Webhook ID'),
		...ConnectionParam,
	},
	async ({ org, hook_id, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/hooks/${enc(hook_id)}`)),
);

registerTool(
	'git_org_webhook_edit',
	'Edit a webhook for an organization',
	{
		org: z.string().describe('Organization name'),
		hook_id: z.number().describe('Webhook ID'),
		url: z.string().optional().describe('New webhook URL'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ org, hook_id, url, events, active, connection }) => {
		const body: Record<string, unknown> = {};
		if (url !== undefined) body.config = { url, content_type: 'json' };
		if (events !== undefined) body.events = events;
		if (active !== undefined) body.active = active;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}/hooks/${enc(hook_id)}`, body));
	},
);

registerTool(
	'git_org_webhook_delete',
	'Delete a webhook for an organization',
	{
		org: z.string().describe('Organization name'),
		hook_id: z.number().describe('Webhook ID'),
		...ConnectionParam,
	},
	async ({ org, hook_id, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/hooks/${enc(hook_id)}`)),
);

registerTool(
	'git_user_webhook_create',
	'Create a webhook for the authenticated user',
	{
		type: z.enum(['git', 'slack', 'discord', 'dingtalk', 'telegram', 'msteams', 'feishu', 'matrix', 'wechatwork', 'packagist']).describe('Hook type'),
		url: z.string().describe('Webhook URL'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ type, url, events, active, connection }) => {
		const body: Record<string, unknown> = {
			type,
			config: { url, content_type: 'json' },
			events: events ?? ['push'],
			active: active ?? true,
		};
		return formatResponse(await clientFor(connection).post(`/user/hooks`, body));
	},
);

registerTool(
	'git_user_webhook_list',
	'List webhooks for the authenticated user',
	{
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get(`/user/hooks`, pageQuery({ page, limit }))),
);

registerTool(
	'git_user_webhook_get',
	'Get a single webhook for the authenticated user',
	{
		hook_id: z.number().describe('Webhook ID'),
		...ConnectionParam,
	},
	async ({ hook_id, connection }) => formatResponse(await clientFor(connection).get(`/user/hooks/${enc(hook_id)}`)),
);

registerTool(
	'git_user_webhook_edit',
	'Edit a webhook for the authenticated user',
	{
		hook_id: z.number().describe('Webhook ID'),
		url: z.string().optional().describe('New webhook URL'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ hook_id, url, events, active, connection }) => {
		const body: Record<string, unknown> = {};
		if (url !== undefined) body.config = { url, content_type: 'json' };
		if (events !== undefined) body.events = events;
		if (active !== undefined) body.active = active;
		return formatResponse(await clientFor(connection).patch(`/user/hooks/${enc(hook_id)}`, body));
	},
);

registerTool(
	'git_user_webhook_delete',
	'Delete a webhook for the authenticated user',
	{
		hook_id: z.number().describe('Webhook ID'),
		...ConnectionParam,
	},
	async ({ hook_id, connection }) => formatResponse(await clientFor(connection).delete(`/user/hooks/${enc(hook_id)}`)),
);

registerTool(
	'git_admin_webhook_create',
	'Create a system-wide (admin) webhook',
	{
		type: z.enum(['git', 'slack', 'discord', 'dingtalk', 'telegram', 'msteams', 'feishu', 'matrix', 'wechatwork', 'packagist']).describe('Hook type'),
		url: z.string().describe('Webhook URL'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ type, url, events, active, connection }) => {
		const body: Record<string, unknown> = {
			type,
			config: { url, content_type: 'json' },
			events: events ?? ['push'],
			active: active ?? true,
		};
		return formatResponse(await clientFor(connection).post(`/admin/hooks`, body));
	},
);

registerTool(
	'git_admin_webhook_list',
	'List system-wide (admin) webhooks',
	{
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get(`/admin/hooks`, pageQuery({ page, limit }))),
);

registerTool(
	'git_admin_webhook_get',
	'Get a single system-wide (admin) webhook',
	{
		hook_id: z.number().describe('Webhook ID'),
		...ConnectionParam,
	},
	async ({ hook_id, connection }) => formatResponse(await clientFor(connection).get(`/admin/hooks/${enc(hook_id)}`)),
);

registerTool(
	'git_admin_webhook_edit',
	'Edit a system-wide (admin) webhook',
	{
		hook_id: z.number().describe('Webhook ID'),
		url: z.string().optional().describe('New webhook URL'),
		events: z.array(z.string()).optional().describe('Events to listen for (e.g. ["push", "pull_request"])'),
		active: z.boolean().optional().describe('Active status'),
		...ConnectionParam,
	},
	async ({ hook_id, url, events, active, connection }) => {
		const body: Record<string, unknown> = {};
		if (url !== undefined) body.config = { url, content_type: 'json' };
		if (events !== undefined) body.events = events;
		if (active !== undefined) body.active = active;
		return formatResponse(await clientFor(connection).patch(`/admin/hooks/${enc(hook_id)}`, body));
	},
);

registerTool(
	'git_admin_webhook_delete',
	'Delete a system-wide (admin) webhook',
	{
		hook_id: z.number().describe('Webhook ID'),
		...ConnectionParam,
	},
	async ({ hook_id, connection }) => formatResponse(await clientFor(connection).delete(`/admin/hooks/${enc(hook_id)}`)),
);

// ── Tag Protection (repo & org) ──────────────────────────────

registerTool(
	'git_tag_protection_list',
	'List tag protections for a repository',
	{ ...OwnerRepo, ...PaginationParams, ...ConnectionParam },
	async ({ owner, repo, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/tag_protections`, pageQuery({ page, limit }))),
);

registerTool(
	'git_tag_protection_get',
	'Get a single tag protection for a repository by ID',
	{ ...OwnerRepo, id: z.number().describe('Tag protection ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/tag_protections/${enc(id)}`)),
);

registerTool(
	'git_tag_protection_create',
	'Create a tag protection for a repository',
	{
		...OwnerRepo,
		name_pattern: z.string().describe('Tag name pattern (glob or regex) to protect'),
		whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to create/delete matching tags'),
		whitelist_teams: z.array(z.string()).optional().describe('Team names allowed to create/delete matching tags'),
		...ConnectionParam,
	},
	async ({ owner, repo, name_pattern, whitelist_usernames, whitelist_teams, connection }) => {
		const body: Record<string, unknown> = { name_pattern };
		if (whitelist_usernames) body.whitelist_usernames = whitelist_usernames;
		if (whitelist_teams) body.whitelist_teams = whitelist_teams;
		return formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/tag_protections`, body));
	},
);

registerTool(
	'git_tag_protection_edit',
	'Edit a tag protection for a repository',
	{
		...OwnerRepo,
		id: z.number().describe('Tag protection ID'),
		name_pattern: z.string().optional().describe('New tag name pattern (glob or regex) to protect'),
		whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to create/delete matching tags'),
		whitelist_teams: z.array(z.string()).optional().describe('Team names allowed to create/delete matching tags'),
		...ConnectionParam,
	},
	async ({ owner, repo, id, name_pattern, whitelist_usernames, whitelist_teams, connection }) => {
		const body: Record<string, unknown> = {};
		if (name_pattern !== undefined) body.name_pattern = name_pattern;
		if (whitelist_usernames) body.whitelist_usernames = whitelist_usernames;
		if (whitelist_teams) body.whitelist_teams = whitelist_teams;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/tag_protections/${enc(id)}`, body));
	},
);

registerTool(
	'git_tag_protection_delete',
	'Delete a tag protection from a repository',
	{ ...OwnerRepo, id: z.number().describe('Tag protection ID'), ...ConnectionParam },
	async ({ owner, repo, id, connection }) => formatResponse(await clientFor(connection).delete(`/repos/${enc(owner)}/${enc(repo)}/tag_protections/${enc(id)}`)),
);

registerTool(
	'git_org_tag_protection_list',
	'List tag protections for an organization',
	{ org: z.string().describe('Organization name'), ...PaginationParams, ...ConnectionParam },
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/tag_protections`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_tag_protection_get',
	'Get a single tag protection for an organization by ID',
	{ org: z.string().describe('Organization name'), id: z.number().describe('Tag protection ID'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/tag_protections/${enc(id)}`)),
);

registerTool(
	'git_org_tag_protection_create',
	'Create a tag protection for an organization',
	{
		org: z.string().describe('Organization name'),
		name_pattern: z.string().describe('Tag name pattern (glob or regex) to protect'),
		whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to create/delete matching tags'),
		whitelist_teams: z.array(z.string()).optional().describe('Team names allowed to create/delete matching tags'),
		...ConnectionParam,
	},
	async ({ org, name_pattern, whitelist_usernames, whitelist_teams, connection }) => {
		const body: Record<string, unknown> = { name_pattern };
		if (whitelist_usernames) body.whitelist_usernames = whitelist_usernames;
		if (whitelist_teams) body.whitelist_teams = whitelist_teams;
		return formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/tag_protections`, body));
	},
);

registerTool(
	'git_org_tag_protection_edit',
	'Edit a tag protection for an organization',
	{
		org: z.string().describe('Organization name'),
		id: z.number().describe('Tag protection ID'),
		name_pattern: z.string().optional().describe('New tag name pattern (glob or regex) to protect'),
		whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to create/delete matching tags'),
		whitelist_teams: z.array(z.string()).optional().describe('Team names allowed to create/delete matching tags'),
		...ConnectionParam,
	},
	async ({ org, id, name_pattern, whitelist_usernames, whitelist_teams, connection }) => {
		const body: Record<string, unknown> = {};
		if (name_pattern !== undefined) body.name_pattern = name_pattern;
		if (whitelist_usernames) body.whitelist_usernames = whitelist_usernames;
		if (whitelist_teams) body.whitelist_teams = whitelist_teams;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}/tag_protections/${enc(id)}`, body));
	},
);

registerTool(
	'git_org_tag_protection_delete',
	'Delete a tag protection from an organization',
	{ org: z.string().describe('Organization name'), id: z.number().describe('Tag protection ID'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/tag_protections/${enc(id)}`)),
);

// ── Sync Profiles (org-level platform-typed content sync, issue #872) ─────────

registerTool(
	'git_org_sync_profile_list',
	"List the organization's sync profiles",
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/sync-profiles`)),
);

registerTool(
	'git_org_sync_profile_get',
	'Get a single sync profile of the organization by ID',
	{ org: z.string().describe('Organization name'), id: z.number().describe('Sync profile ID'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/sync-profiles/${enc(id)}`)),
);

registerTool(
	'git_org_sync_profile_create',
	'Create a sync profile for the organization (distributes source content to platform-matched member repos)',
	{
		org: z.string().describe('Organization name'),
		name: z.string().describe('Profile name (unique per org)'),
		source_repo_id: z.number().describe('Source template repository ID — content is read from here'),
		platform: z.string().describe('Platform metadata value that selects member repos (e.g. go, npm, php, joomla, generic)'),
		source_branch: z.string().optional().describe('Source branch (default: the source repo default branch)'),
		content_globs: z.string().optional().describe('Newline-separated path globs to sync; empty uses the built-in defaults (.mokogit/workflows/**, .mokogit/actions/**, ISSUE_TEMPLATE/**). The custom/ subtrees are always excluded.'),
		applies_to: z.string().optional().describe('Newline-separated Go regexes matched at sync time against each candidate repo\'s root Makefile; a repo becomes a member if ANY regex matches (e.g. "(?m)^\\\\s*PLATFORM\\\\s*[:?]?=\\\\s*go\\\\b" matches repos whose Makefile declares PLATFORM = go). Unioned with the `platform` selector, so it matches by Makefile content WITHOUT needing a registered platform. Lines starting with # are comments.'),
		mode: z.enum(['pr', 'direct']).optional().describe("How content is applied: 'pr' (open a PR) or 'direct' (commit to the default branch). Default: pr"),
		is_active: z.boolean().optional().describe('Whether the periodic reconcile applies this profile'),
		...ConnectionParam,
	},
	async ({ org, name, source_repo_id, platform, source_branch, content_globs, applies_to, mode, is_active, connection }) => {
		const body: Record<string, unknown> = { name, source_repo_id, platform };
		if (source_branch !== undefined) body.source_branch = source_branch;
		if (content_globs !== undefined) body.content_globs = content_globs;
		if (applies_to !== undefined) body.applies_to = applies_to;
		if (mode !== undefined) body.mode = mode;
		if (is_active !== undefined) body.is_active = is_active;
		return formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/sync-profiles`, body));
	},
);

registerTool(
	'git_org_sync_profile_edit',
	'Update a sync profile of the organization — only the fields provided are changed',
	{
		org: z.string().describe('Organization name'),
		id: z.number().describe('Sync profile ID'),
		name: z.string().optional().describe('New profile name'),
		source_repo_id: z.number().optional().describe('New source template repository ID'),
		platform: z.string().optional().describe('New platform selector'),
		source_branch: z.string().optional().describe('New source branch'),
		content_globs: z.string().optional().describe('New newline-separated content globs'),
		applies_to: z.string().optional().describe('New newline-separated Go regexes matched against each candidate repo\'s root Makefile at sync time (member if ANY matches; unioned with the platform selector). Lines starting with # are comments.'),
		mode: z.enum(['pr', 'direct']).optional().describe("How content is applied: 'pr' or 'direct'"),
		is_active: z.boolean().optional().describe('Enable/disable periodic reconcile for this profile'),
		...ConnectionParam,
	},
	async ({ org, id, name, source_repo_id, platform, source_branch, content_globs, applies_to, mode, is_active, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body.name = name;
		if (source_repo_id !== undefined) body.source_repo_id = source_repo_id;
		if (platform !== undefined) body.platform = platform;
		if (source_branch !== undefined) body.source_branch = source_branch;
		if (content_globs !== undefined) body.content_globs = content_globs;
		if (applies_to !== undefined) body.applies_to = applies_to;
		if (mode !== undefined) body.mode = mode;
		if (is_active !== undefined) body.is_active = is_active;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}/sync-profiles/${enc(id)}`, body));
	},
);

registerTool(
	'git_org_sync_profile_delete',
	'Delete a sync profile from the organization',
	{ org: z.string().describe('Organization name'), id: z.number().describe('Sync profile ID'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/sync-profiles/${enc(id)}`)),
);

registerTool(
	'git_org_sync_profile_dry_run',
	'Compute the sync plan for a profile (dry-run — no changes are written)',
	{ org: z.string().describe('Organization name'), id: z.number().describe('Sync profile ID'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/sync-profiles/${enc(id)}/sync`)),
);

// NOTE: git_org_sync_profile_apply is registered below as a poll-to-completion
// wrapper (mokogit-mcp #237). The earlier naïve single-shot registration that
// lived here was a duplicate that crashed startup ("Tool git_org_sync_profile_apply
// already registered"); the wrapper's wait=false mode covers the single-shot case.

registerTool(
	'git_org_sync_profile_status',
	"Get a sync profile's live status: resolved target count and real pending drift (pending_changes / in_sync). Read-only — no changes are written.",
	{ org: z.string().describe('Organization name'), id: z.number().describe('Sync profile ID'), ...ConnectionParam },
	async ({ org, id, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/sync-profiles/${enc(id)}/status`)),
);

// ── Branch Protection (edit / get / priorities) ──────────────────────────────

registerTool(
	'git_branch_protection_get',
	'Get a single branch protection rule for a repository',
	{
		...OwnerRepo,
		branch_name: z.string().describe('Branch protection rule name (branch name or pattern, e.g. "main", "release/*")'),
		...ConnectionParam,
	},
	async ({ owner, repo, branch_name, connection }) => formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/branch_protections/${enc(branch_name)}`)),
);

registerTool(
	'git_branch_protection_edit',
	'Edit an existing branch protection rule',
	{
		...OwnerRepo,
		branch_name: z.string().describe('Branch protection rule name (branch name or pattern, e.g. "main", "release/*")'),
		enable_push: z.boolean().optional().describe('Allow push'),
		enable_push_whitelist: z.boolean().optional().describe('Enable push whitelist'),
		push_whitelist_usernames: z.array(z.string()).optional().describe('Users allowed to push'),
		push_whitelist_actions_user: z.boolean().optional().describe('Allow the Actions user to push'),
		enable_force_push: z.boolean().optional().describe('Allow force pushes to matching branches'),
		enable_force_push_allowlist: z.boolean().optional().describe('Restrict force pushes to an allowlist'),
		force_push_allowlist_usernames: z.array(z.string()).optional().describe('Usernames allowed to force push'),
		force_push_allowlist_teams: z.array(z.string()).optional().describe('Teams allowed to force push'),
		force_push_allowlist_actions_user: z.boolean().optional().describe('Allow the Actions user to force push'),
		require_signed_commits: z.boolean().optional().describe('Require signed commits'),
		required_approvals: z.number().optional().describe('Required PR approvals (0 = none)'),
		enable_status_check: z.boolean().optional().describe('Require status checks'),
		status_check_contexts: z.array(z.string()).optional().describe('Required status check names'),
		...ConnectionParam,
	},
	async ({ owner, repo, branch_name, enable_push, enable_push_whitelist, push_whitelist_usernames, push_whitelist_actions_user, enable_force_push, enable_force_push_allowlist, force_push_allowlist_usernames, force_push_allowlist_teams, force_push_allowlist_actions_user, require_signed_commits, required_approvals, enable_status_check, status_check_contexts, connection }) => {
		const body: Record<string, unknown> = {};
		if (enable_push !== undefined) body.enable_push = enable_push;
		if (enable_push_whitelist !== undefined) body.enable_push_whitelist = enable_push_whitelist;
		if (push_whitelist_usernames) body.push_whitelist_usernames = push_whitelist_usernames;
		if (push_whitelist_actions_user !== undefined) body.push_whitelist_actions_user = push_whitelist_actions_user;
		if (enable_force_push !== undefined) body.enable_force_push = enable_force_push;
		if (enable_force_push_allowlist !== undefined) body.enable_force_push_allowlist = enable_force_push_allowlist;
		if (force_push_allowlist_usernames) body.force_push_allowlist_usernames = force_push_allowlist_usernames;
		if (force_push_allowlist_teams) body.force_push_allowlist_teams = force_push_allowlist_teams;
		if (force_push_allowlist_actions_user !== undefined) body.force_push_allowlist_actions_user = force_push_allowlist_actions_user;
		if (require_signed_commits !== undefined) body.require_signed_commits = require_signed_commits;
		if (required_approvals !== undefined) body.required_approvals = required_approvals;
		if (enable_status_check !== undefined) body.enable_status_check = enable_status_check;
		if (status_check_contexts) body.status_check_contexts = status_check_contexts;
		return formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/branch_protections/${enc(branch_name)}`, body));
	},
);

registerTool(
	'git_branch_protection_priorities',
	'Update the priority ordering of branch protection rules for a repository',
	{
		...OwnerRepo,
		ids: z.array(z.number()).describe('Branch protection rule IDs in the desired priority order'),
		...ConnectionParam,
	},
	async ({ owner, repo, ids, connection }) => formatResponse(await clientFor(connection).post(`/repos/${enc(owner)}/${enc(repo)}/branch_protections/priority`, { ids })),
);

// ── Branch Rename / Update ──────────────────────────────

registerTool(
	'git_branch_rename',
	'Rename a branch in a repository (repoRenameBranch)',
	{
		...OwnerRepo,
		branch: z.string().describe('Current branch name to rename'),
		to: z.string().describe('New branch name'),
		...ConnectionParam,
	},
	async ({ owner, repo, branch, to, connection }) =>
		formatResponse(await clientFor(connection).patch(`/repos/${enc(owner)}/${enc(repo)}/branches/${enc(branch)}`, { to })),
);

registerTool(
	'git_branch_update',
	'Update a branch in a repository (repoUpdateBranch)',
	{
		...OwnerRepo,
		branch: z.string().describe('Branch name to update'),
		name: z.string().optional().describe('New branch name'),
		...ConnectionParam,
	},
	async ({ owner, repo, branch, name, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body.name = name;
		return formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/branches/${enc(branch)}`, body));
	},
);

// ── Organization CRUD & Avatar ──────────────────────────────

registerTool(
	'git_orgs_list',
	'List all organizations (admin/global listing)',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/orgs', pageQuery({ page, limit }))),
);

registerTool(
	'git_org_create',
	'Create a new organization',
	{
		username: z.string().describe('Organization username (name)'),
		full_name: z.string().optional().describe('Full display name'),
		description: z.string().optional().describe('Organization description'),
		website: z.string().optional().describe('Organization website URL'),
		location: z.string().optional().describe('Organization location'),
		visibility: z.enum(['public', 'limited', 'private']).optional().describe('Organization visibility'),
		repo_admin_change_team_access: z.boolean().optional().describe('Allow repo admins to change team access'),
		...ConnectionParam,
	},
	async ({ username, full_name, description, website, location, visibility, repo_admin_change_team_access, connection }) => {
		const body: Record<string, unknown> = { username };
		if (full_name !== undefined) body.full_name = full_name;
		if (description !== undefined) body.description = description;
		if (website !== undefined) body.website = website;
		if (location !== undefined) body.location = location;
		if (visibility !== undefined) body.visibility = visibility;
		if (repo_admin_change_team_access !== undefined) body.repo_admin_change_team_access = repo_admin_change_team_access;
		return formatResponse(await clientFor(connection).post('/orgs', body));
	},
);

registerTool(
	'git_org_edit',
	'Edit an existing organization',
	{
		org: z.string().describe('Organization name'),
		full_name: z.string().optional().describe('Full display name'),
		description: z.string().optional().describe('Organization description'),
		website: z.string().optional().describe('Organization website URL'),
		location: z.string().optional().describe('Organization location'),
		visibility: z.enum(['public', 'limited', 'private']).optional().describe('Organization visibility'),
		repo_admin_change_team_access: z.boolean().optional().describe('Allow repo admins to change team access'),
		...ConnectionParam,
	},
	async ({ org, full_name, description, website, location, visibility, repo_admin_change_team_access, connection }) => {
		const body: Record<string, unknown> = {};
		if (full_name !== undefined) body.full_name = full_name;
		if (description !== undefined) body.description = description;
		if (website !== undefined) body.website = website;
		if (location !== undefined) body.location = location;
		if (visibility !== undefined) body.visibility = visibility;
		if (repo_admin_change_team_access !== undefined) body.repo_admin_change_team_access = repo_admin_change_team_access;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}`, body));
	},
);

registerTool(
	'git_org_delete',
	'Delete an organization',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}`)),
);

registerTool(
	'git_org_rename',
	'Rename an organization',
	{
		org: z.string().describe('Current organization name'),
		new_name: z.string().describe('New organization name'),
		...ConnectionParam,
	},
	async ({ org, new_name, connection }) => formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/rename`, { new_name })),
);

registerTool(
	'git_org_avatar_update',
	'Update an organization avatar (provide base64-encoded image content)',
	{
		org: z.string().describe('Organization name'),
		image_base64: z.string().describe('Base64-encoded image content'),
		...ConnectionParam,
	},
	async ({ org, image_base64, connection }) => formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/avatar`, { image: image_base64 })),
);

registerTool(
	'git_org_avatar_delete',
	'Delete an organization avatar',
	{ org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ org, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/avatar`)),
);

// ── Organization Teams ──────────────────────────────

registerTool(
	'git_org_team_create',
	'Create a team in an organization (POST /orgs/{org}/teams)',
	{
		org: z.string().describe('Organization name'),
		name: z.string().describe('Team name'),
		description: z.string().optional().describe('Team description'),
		permission: z.enum(['read', 'write', 'admin']).optional().describe('Team permission level'),
		units: z.array(z.string()).optional().describe('Repository units the team can access (e.g. ["repo.code", "repo.issues", "repo.pulls"])'),
		units_map: z.record(z.string()).optional().describe('Map of unit name to access level (overrides units)'),
		can_create_org_repo: z.boolean().optional().describe('Allow team members to create org repositories'),
		includes_all_repositories: z.boolean().optional().describe('Grant the team access to all org repositories'),
		...ConnectionParam,
	},
	async ({ org, name, description, permission, units, units_map, can_create_org_repo, includes_all_repositories, connection }) => {
		const body: Record<string, unknown> = { name };
		if (description !== undefined) body.description = description;
		if (permission !== undefined) body.permission = permission;
		if (units !== undefined) body.units = units;
		if (units_map !== undefined) body.units_map = units_map;
		if (can_create_org_repo !== undefined) body.can_create_org_repo = can_create_org_repo;
		if (includes_all_repositories !== undefined) body.includes_all_repositories = includes_all_repositories;
		return formatResponse(await clientFor(connection).post(`/orgs/${enc(org)}/teams`, body));
	},
);

registerTool(
	'git_team_get',
	'Get a team by its ID (GET /teams/{id})',
	{ team_id: z.number().describe('Team ID'), ...ConnectionParam },
	async ({ team_id, connection }) => formatResponse(await clientFor(connection).get(`/teams/${enc(team_id)}`)),
);

registerTool(
	'git_team_edit',
	'Edit a team by its ID (PATCH /teams/{id})',
	{
		team_id: z.number().describe('Team ID'),
		name: z.string().optional().describe('Team name'),
		description: z.string().optional().describe('Team description'),
		permission: z.enum(['read', 'write', 'admin']).optional().describe('Team permission level'),
		units: z.array(z.string()).optional().describe('Repository units the team can access (e.g. ["repo.code", "repo.issues", "repo.pulls"])'),
		units_map: z.record(z.string()).optional().describe('Map of unit name to access level (overrides units)'),
		can_create_org_repo: z.boolean().optional().describe('Allow team members to create org repositories'),
		includes_all_repositories: z.boolean().optional().describe('Grant the team access to all org repositories'),
		...ConnectionParam,
	},
	async ({ team_id, name, description, permission, units, units_map, can_create_org_repo, includes_all_repositories, connection }) => {
		const body: Record<string, unknown> = {};
		if (name !== undefined) body.name = name;
		if (description !== undefined) body.description = description;
		if (permission !== undefined) body.permission = permission;
		if (units !== undefined) body.units = units;
		if (units_map !== undefined) body.units_map = units_map;
		if (can_create_org_repo !== undefined) body.can_create_org_repo = can_create_org_repo;
		if (includes_all_repositories !== undefined) body.includes_all_repositories = includes_all_repositories;
		return formatResponse(await clientFor(connection).patch(`/teams/${enc(team_id)}`, body));
	},
);

registerTool(
	'git_team_delete',
	'Delete a team by its ID (DELETE /teams/{id})',
	{ team_id: z.number().describe('Team ID'), ...ConnectionParam },
	async ({ team_id, connection }) => formatResponse(await clientFor(connection).delete(`/teams/${enc(team_id)}`)),
);

registerTool(
	'git_team_members_list',
	'List members of a team (GET /teams/{id}/members)',
	{ team_id: z.number().describe('Team ID'), ...PaginationParams, ...ConnectionParam },
	async ({ team_id, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/teams/${enc(team_id)}/members`, pageQuery({ page, limit }))),
);

registerTool(
	'git_team_member_get',
	'Get a specific member of a team (GET /teams/{id}/members/{username})',
	{ team_id: z.number().describe('Team ID'), username: z.string().describe('Member username'), ...ConnectionParam },
	async ({ team_id, username, connection }) => formatResponse(await clientFor(connection).get(`/teams/${enc(team_id)}/members/${enc(username)}`)),
);

registerTool(
	'git_team_member_add',
	'Add a member to a team (PUT /teams/{id}/members/{username})',
	{ team_id: z.number().describe('Team ID'), username: z.string().describe('Username to add'), ...ConnectionParam },
	async ({ team_id, username, connection }) => formatResponse(await clientFor(connection).put(`/teams/${enc(team_id)}/members/${enc(username)}`, {})),
);

registerTool(
	'git_team_member_remove',
	'Remove a member from a team (DELETE /teams/{id}/members/{username})',
	{ team_id: z.number().describe('Team ID'), username: z.string().describe('Username to remove'), ...ConnectionParam },
	async ({ team_id, username, connection }) => formatResponse(await clientFor(connection).delete(`/teams/${enc(team_id)}/members/${enc(username)}`)),
);

registerTool(
	'git_team_repos_list',
	'List repositories assigned to a team (GET /teams/{id}/repos)',
	{ team_id: z.number().describe('Team ID'), ...PaginationParams, ...ConnectionParam },
	async ({ team_id, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/teams/${enc(team_id)}/repos`, pageQuery({ page, limit }))),
);

registerTool(
	'git_team_repo_get',
	'Get a specific repository assigned to a team (GET /teams/{id}/repos/{org}/{repo})',
	{ team_id: z.number().describe('Team ID'), org: z.string().describe('Organization name'), repo: z.string().describe('Repository name'), ...ConnectionParam },
	async ({ team_id, org, repo, connection }) => formatResponse(await clientFor(connection).get(`/teams/${enc(team_id)}/repos/${enc(org)}/${enc(repo)}`)),
);

registerTool(
	'git_team_repo_add',
	'Add a repository to a team (PUT /teams/{id}/repos/{org}/{repo})',
	{ team_id: z.number().describe('Team ID'), org: z.string().describe('Organization name'), repo: z.string().describe('Repository name'), ...ConnectionParam },
	async ({ team_id, org, repo, connection }) => formatResponse(await clientFor(connection).put(`/teams/${enc(team_id)}/repos/${enc(org)}/${enc(repo)}`, {})),
);

registerTool(
	'git_team_repo_remove',
	'Remove a repository from a team (DELETE /teams/{id}/repos/{org}/{repo})',
	{ team_id: z.number().describe('Team ID'), org: z.string().describe('Organization name'), repo: z.string().describe('Repository name'), ...ConnectionParam },
	async ({ team_id, org, repo, connection }) => formatResponse(await clientFor(connection).delete(`/teams/${enc(team_id)}/repos/${enc(org)}/${enc(repo)}`)),
);

registerTool(
	'git_team_search',
	'Search for teams within an organization (GET /orgs/{org}/teams/search)',
	{
		org: z.string().describe('Organization name'),
		q: z.string().optional().describe('Search query keyword'),
		include_desc: z.boolean().optional().describe('Include the team description in the search'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ org, q, include_desc, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (q !== undefined) params['q'] = q;
		if (include_desc !== undefined) params['include_desc'] = String(include_desc);
		return formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/teams/search`, params));
	},
);

registerTool(
	'git_user_org_permissions_get',
	"Get a user's permissions within an organization (GET /users/{username}/orgs/{org}/permissions)",
	{ username: z.string().describe('Username'), org: z.string().describe('Organization name'), ...ConnectionParam },
	async ({ username, org, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/orgs/${enc(org)}/permissions`)),
);

// ── Organization Membership ──────────────────────────────

registerTool(
	'git_org_membership_check',
	'Check whether a user is a member of an organization',
	{
		org: z.string().describe('Organization name'),
		username: z.string().describe('Username of the member to check'),
		...ConnectionParam,
	},
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/members/${enc(username)}`)),
);

registerTool(
	'git_org_membership_remove',
	'Remove a member from an organization',
	{
		org: z.string().describe('Organization name'),
		username: z.string().describe('Username of the member to remove'),
		...ConnectionParam,
	},
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/members/${enc(username)}`)),
);

registerTool(
	'git_org_public_members_list',
	'List the public members of an organization',
	{
		org: z.string().describe('Organization name'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ org, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/public_members`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_public_members_check',
	'Check whether a user is a public member of an organization',
	{
		org: z.string().describe('Organization name'),
		username: z.string().describe('Username of the member to check'),
		...ConnectionParam,
	},
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/public_members/${enc(username)}`)),
);

registerTool(
	'git_org_public_members_publicize',
	'Publicize a user\'s membership in an organization (make it public)',
	{
		org: z.string().describe('Organization name'),
		username: z.string().describe('Username of the member to publicize'),
		...ConnectionParam,
	},
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).put(`/orgs/${enc(org)}/public_members/${enc(username)}`, {})),
);

registerTool(
	'git_org_public_members_conceal',
	'Conceal a user\'s membership in an organization (make it private)',
	{
		org: z.string().describe('Organization name'),
		username: z.string().describe('Username of the member to conceal'),
		...ConnectionParam,
	},
	async ({ org, username, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/public_members/${enc(username)}`)),
);

// ── Organization Governance (Moko) ──────────────────────────────

registerTool(
	'git_org_governance_branch_protections_list',
	'List branch protection rules for an organization',
	{
		org: z.string().describe('Organization name'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ org, page, limit, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/branch_protections`, pageQuery({ page, limit }))),
);

registerTool(
	'git_org_governance_branch_protection_create',
	'Create a branch protection rule for an organization',
	{
		org: z.string().describe('Organization name'),
		rule_name: z.string().optional().describe('Name/pattern of the branch protection rule (e.g. "main")'),
		enable_push: z.boolean().optional().describe('Allow pushes to matching branches'),
		enable_push_whitelist: z.boolean().optional().describe('Restrict pushes to whitelisted users'),
		push_whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to push'),
		push_whitelist_teams: z.array(z.string()).optional().describe('Teams allowed to push'),
		push_whitelist_actions_user: z.boolean().optional().describe('Allow the Actions user to push'),
		enable_force_push: z.boolean().optional().describe('Allow force pushes to matching branches'),
		enable_force_push_allowlist: z.boolean().optional().describe('Restrict force pushes to an allowlist'),
		force_push_allowlist_usernames: z.array(z.string()).optional().describe('Usernames allowed to force push'),
		force_push_allowlist_teams: z.array(z.string()).optional().describe('Teams allowed to force push'),
		force_push_allowlist_actions_user: z.boolean().optional().describe('Allow the Actions user to force push'),
		enable_delete: z.boolean().optional().describe('Allow deletion of matching branches'),
		enable_delete_allowlist: z.boolean().optional().describe('Restrict branch deletion to an allowlist'),
		delete_allowlist_usernames: z.array(z.string()).optional().describe('Usernames allowed to delete branches'),
		delete_allowlist_teams: z.array(z.string()).optional().describe('Teams allowed to delete branches'),
		delete_allowlist_actions_user: z.boolean().optional().describe('Allow the Actions user to delete branches'),
		enable_merge_whitelist: z.boolean().optional().describe('Restrict merges to whitelisted users'),
		merge_whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to merge'),
		merge_whitelist_teams: z.array(z.string()).optional().describe('Teams allowed to merge'),
		enable_status_check: z.boolean().optional().describe('Require status checks to pass'),
		status_check_contexts: z.array(z.string()).optional().describe('Required status check contexts'),
		required_approvals: z.number().optional().describe('Number of required approvals'),
		enable_approvals_whitelist: z.boolean().optional().describe('Restrict approvals to whitelisted users'),
		approvals_whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to approve'),
		approvals_whitelist_teams: z.array(z.string()).optional().describe('Teams allowed to approve'),
		block_on_rejected_reviews: z.boolean().optional().describe('Block merge on rejected reviews'),
		block_on_official_review_requests: z.boolean().optional().describe('Block merge on pending official review requests'),
		block_on_outdated_branch: z.boolean().optional().describe('Block merge when branch is outdated'),
		dismiss_stale_approvals: z.boolean().optional().describe('Dismiss stale approvals on new commits'),
		require_signed_commits: z.boolean().optional().describe('Require signed commits'),
		protected_file_patterns: z.string().optional().describe('Protected file patterns (semicolon-separated globs)'),
		unprotected_file_patterns: z.string().optional().describe('Unprotected file patterns (semicolon-separated globs)'),
		...ConnectionParam,
	},
	async ({ org, rule_name, enable_push, enable_push_whitelist, push_whitelist_usernames, push_whitelist_teams, push_whitelist_actions_user, enable_force_push, enable_force_push_allowlist, force_push_allowlist_usernames, force_push_allowlist_teams, force_push_allowlist_actions_user, enable_delete, enable_delete_allowlist, delete_allowlist_usernames, delete_allowlist_teams, delete_allowlist_actions_user, enable_merge_whitelist, merge_whitelist_usernames, merge_whitelist_teams, enable_status_check, status_check_contexts, required_approvals, enable_approvals_whitelist, approvals_whitelist_usernames, approvals_whitelist_teams, block_on_rejected_reviews, block_on_official_review_requests, block_on_outdated_branch, dismiss_stale_approvals, require_signed_commits, protected_file_patterns, unprotected_file_patterns, connection }) => {
		const body: Record<string, unknown> = {};
		if (rule_name !== undefined) body.rule_name = rule_name;
		if (enable_push !== undefined) body.enable_push = enable_push;
		if (enable_push_whitelist !== undefined) body.enable_push_whitelist = enable_push_whitelist;
		if (push_whitelist_usernames !== undefined) body.push_whitelist_usernames = push_whitelist_usernames;
		if (push_whitelist_teams !== undefined) body.push_whitelist_teams = push_whitelist_teams;
		if (push_whitelist_actions_user !== undefined) body.push_whitelist_actions_user = push_whitelist_actions_user;
		if (enable_force_push !== undefined) body.enable_force_push = enable_force_push;
		if (enable_force_push_allowlist !== undefined) body.enable_force_push_allowlist = enable_force_push_allowlist;
		if (force_push_allowlist_usernames !== undefined) body.force_push_allowlist_usernames = force_push_allowlist_usernames;
		if (force_push_allowlist_teams !== undefined) body.force_push_allowlist_teams = force_push_allowlist_teams;
		if (force_push_allowlist_actions_user !== undefined) body.force_push_allowlist_actions_user = force_push_allowlist_actions_user;
		if (enable_delete !== undefined) body.enable_delete = enable_delete;
		if (enable_delete_allowlist !== undefined) body.enable_delete_allowlist = enable_delete_allowlist;
		if (delete_allowlist_usernames !== undefined) body.delete_allowlist_usernames = delete_allowlist_usernames;
		if (delete_allowlist_teams !== undefined) body.delete_allowlist_teams = delete_allowlist_teams;
		if (delete_allowlist_actions_user !== undefined) body.delete_allowlist_actions_user = delete_allowlist_actions_user;
		if (enable_merge_whitelist !== undefined) body.enable_merge_whitelist = enable_merge_whitelist;
		if (merge_whitelist_usernames !== undefined) body.merge_whitelist_usernames = merge_whitelist_usernames;
		if (merge_whitelist_teams !== undefined) body.merge_whitelist_teams = merge_whitelist_teams;
		if (enable_status_check !== undefined) body.enable_status_check = enable_status_check;
		if (status_check_contexts !== undefined) body.status_check_contexts = status_check_contexts;
		if (required_approvals !== undefined) body.required_approvals = required_approvals;
		if (enable_approvals_whitelist !== undefined) body.enable_approvals_whitelist = enable_approvals_whitelist;
		if (approvals_whitelist_usernames !== undefined) body.approvals_whitelist_usernames = approvals_whitelist_usernames;
		if (approvals_whitelist_teams !== undefined) body.approvals_whitelist_teams = approvals_whitelist_teams;
		if (block_on_rejected_reviews !== undefined) body.block_on_rejected_reviews = block_on_rejected_reviews;
		if (block_on_official_review_requests !== undefined) body.block_on_official_review_requests = block_on_official_review_requests;
		if (block_on_outdated_branch !== undefined) body.block_on_outdated_branch = block_on_outdated_branch;
		if (dismiss_stale_approvals !== undefined) body.dismiss_stale_approvals = dismiss_stale_approvals;
		if (require_signed_commits !== undefined) body.require_signed_commits = require_signed_commits;
		if (protected_file_patterns !== undefined) body.protected_file_patterns = protected_file_patterns;
		if (unprotected_file_patterns !== undefined) body.unprotected_file_patterns = unprotected_file_patterns;
		return formatResponse(await clientV2For(connection).post(`/orgs/${enc(org)}/branch_protections`, body));
	},
);

registerTool(
	'git_org_governance_branch_protection_get',
	'Get a single branch protection rule for an organization',
	{
		org: z.string().describe('Organization name'),
		name: z.string().describe('Branch protection rule name/pattern'),
		...ConnectionParam,
	},
	async ({ org, name, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/branch_protections/${enc(name)}`)),
);

registerTool(
	'git_org_governance_branch_protection_edit',
	'Edit a branch protection rule for an organization',
	{
		org: z.string().describe('Organization name'),
		name: z.string().describe('Branch protection rule name/pattern'),
		enable_push: z.boolean().optional().describe('Allow pushes to matching branches'),
		enable_push_whitelist: z.boolean().optional().describe('Restrict pushes to whitelisted users'),
		push_whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to push'),
		push_whitelist_teams: z.array(z.string()).optional().describe('Teams allowed to push'),
		push_whitelist_actions_user: z.boolean().optional().describe('Allow the Actions user to push'),
		enable_force_push: z.boolean().optional().describe('Allow force pushes to matching branches'),
		enable_force_push_allowlist: z.boolean().optional().describe('Restrict force pushes to an allowlist'),
		force_push_allowlist_usernames: z.array(z.string()).optional().describe('Usernames allowed to force push'),
		force_push_allowlist_teams: z.array(z.string()).optional().describe('Teams allowed to force push'),
		force_push_allowlist_actions_user: z.boolean().optional().describe('Allow the Actions user to force push'),
		enable_delete: z.boolean().optional().describe('Allow deletion of matching branches'),
		enable_delete_allowlist: z.boolean().optional().describe('Restrict branch deletion to an allowlist'),
		delete_allowlist_usernames: z.array(z.string()).optional().describe('Usernames allowed to delete branches'),
		delete_allowlist_teams: z.array(z.string()).optional().describe('Teams allowed to delete branches'),
		delete_allowlist_actions_user: z.boolean().optional().describe('Allow the Actions user to delete branches'),
		enable_merge_whitelist: z.boolean().optional().describe('Restrict merges to whitelisted users'),
		merge_whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to merge'),
		merge_whitelist_teams: z.array(z.string()).optional().describe('Teams allowed to merge'),
		enable_status_check: z.boolean().optional().describe('Require status checks to pass'),
		status_check_contexts: z.array(z.string()).optional().describe('Required status check contexts'),
		required_approvals: z.number().optional().describe('Number of required approvals'),
		enable_approvals_whitelist: z.boolean().optional().describe('Restrict approvals to whitelisted users'),
		approvals_whitelist_usernames: z.array(z.string()).optional().describe('Usernames allowed to approve'),
		approvals_whitelist_teams: z.array(z.string()).optional().describe('Teams allowed to approve'),
		block_on_rejected_reviews: z.boolean().optional().describe('Block merge on rejected reviews'),
		block_on_official_review_requests: z.boolean().optional().describe('Block merge on pending official review requests'),
		block_on_outdated_branch: z.boolean().optional().describe('Block merge when branch is outdated'),
		dismiss_stale_approvals: z.boolean().optional().describe('Dismiss stale approvals on new commits'),
		require_signed_commits: z.boolean().optional().describe('Require signed commits'),
		protected_file_patterns: z.string().optional().describe('Protected file patterns (semicolon-separated globs)'),
		unprotected_file_patterns: z.string().optional().describe('Unprotected file patterns (semicolon-separated globs)'),
		...ConnectionParam,
	},
	async ({ org, name, enable_push, enable_push_whitelist, push_whitelist_usernames, push_whitelist_teams, push_whitelist_actions_user, enable_force_push, enable_force_push_allowlist, force_push_allowlist_usernames, force_push_allowlist_teams, force_push_allowlist_actions_user, enable_delete, enable_delete_allowlist, delete_allowlist_usernames, delete_allowlist_teams, delete_allowlist_actions_user, enable_merge_whitelist, merge_whitelist_usernames, merge_whitelist_teams, enable_status_check, status_check_contexts, required_approvals, enable_approvals_whitelist, approvals_whitelist_usernames, approvals_whitelist_teams, block_on_rejected_reviews, block_on_official_review_requests, block_on_outdated_branch, dismiss_stale_approvals, require_signed_commits, protected_file_patterns, unprotected_file_patterns, connection }) => {
		const body: Record<string, unknown> = {};
		if (enable_push !== undefined) body.enable_push = enable_push;
		if (enable_push_whitelist !== undefined) body.enable_push_whitelist = enable_push_whitelist;
		if (push_whitelist_usernames !== undefined) body.push_whitelist_usernames = push_whitelist_usernames;
		if (push_whitelist_teams !== undefined) body.push_whitelist_teams = push_whitelist_teams;
		if (push_whitelist_actions_user !== undefined) body.push_whitelist_actions_user = push_whitelist_actions_user;
		if (enable_force_push !== undefined) body.enable_force_push = enable_force_push;
		if (enable_force_push_allowlist !== undefined) body.enable_force_push_allowlist = enable_force_push_allowlist;
		if (force_push_allowlist_usernames !== undefined) body.force_push_allowlist_usernames = force_push_allowlist_usernames;
		if (force_push_allowlist_teams !== undefined) body.force_push_allowlist_teams = force_push_allowlist_teams;
		if (force_push_allowlist_actions_user !== undefined) body.force_push_allowlist_actions_user = force_push_allowlist_actions_user;
		if (enable_delete !== undefined) body.enable_delete = enable_delete;
		if (enable_delete_allowlist !== undefined) body.enable_delete_allowlist = enable_delete_allowlist;
		if (delete_allowlist_usernames !== undefined) body.delete_allowlist_usernames = delete_allowlist_usernames;
		if (delete_allowlist_teams !== undefined) body.delete_allowlist_teams = delete_allowlist_teams;
		if (delete_allowlist_actions_user !== undefined) body.delete_allowlist_actions_user = delete_allowlist_actions_user;
		if (enable_merge_whitelist !== undefined) body.enable_merge_whitelist = enable_merge_whitelist;
		if (merge_whitelist_usernames !== undefined) body.merge_whitelist_usernames = merge_whitelist_usernames;
		if (merge_whitelist_teams !== undefined) body.merge_whitelist_teams = merge_whitelist_teams;
		if (enable_status_check !== undefined) body.enable_status_check = enable_status_check;
		if (status_check_contexts !== undefined) body.status_check_contexts = status_check_contexts;
		if (required_approvals !== undefined) body.required_approvals = required_approvals;
		if (enable_approvals_whitelist !== undefined) body.enable_approvals_whitelist = enable_approvals_whitelist;
		if (approvals_whitelist_usernames !== undefined) body.approvals_whitelist_usernames = approvals_whitelist_usernames;
		if (approvals_whitelist_teams !== undefined) body.approvals_whitelist_teams = approvals_whitelist_teams;
		if (block_on_rejected_reviews !== undefined) body.block_on_rejected_reviews = block_on_rejected_reviews;
		if (block_on_official_review_requests !== undefined) body.block_on_official_review_requests = block_on_official_review_requests;
		if (block_on_outdated_branch !== undefined) body.block_on_outdated_branch = block_on_outdated_branch;
		if (dismiss_stale_approvals !== undefined) body.dismiss_stale_approvals = dismiss_stale_approvals;
		if (require_signed_commits !== undefined) body.require_signed_commits = require_signed_commits;
		if (protected_file_patterns !== undefined) body.protected_file_patterns = protected_file_patterns;
		if (unprotected_file_patterns !== undefined) body.unprotected_file_patterns = unprotected_file_patterns;
		return formatResponse(await clientV2For(connection).patch(`/orgs/${enc(org)}/branch_protections/${enc(name)}`, body));
	},
);

registerTool(
	'git_org_governance_branch_protection_delete',
	'Delete a branch protection rule for an organization',
	{
		org: z.string().describe('Organization name'),
		name: z.string().describe('Branch protection rule name/pattern'),
		...ConnectionParam,
	},
	async ({ org, name, connection }) => formatResponse(await clientV2For(connection).delete(`/orgs/${enc(org)}/branch_protections/${enc(name)}`)),
);

registerTool(
	'git_org_policy_push_policy_get',
	'Get the push policy for an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/push_policy`)),
);

registerTool(
	'git_org_policy_push_policy_edit',
	'Edit the push policy for an organization',
	{
		org: z.string().describe('Organization name'),
		require_signed_commits: z.boolean().optional().describe('Require signed commits on push'),
		block_force_push: z.boolean().optional().describe('Block force pushes'),
		max_file_size: z.number().optional().describe('Maximum allowed pushed file size (bytes)'),
		allowed_file_patterns: z.string().optional().describe('Allowed file patterns (semicolon-separated globs)'),
		blocked_file_patterns: z.string().optional().describe('Blocked file patterns (semicolon-separated globs)'),
		...ConnectionParam,
	},
	async ({ org, require_signed_commits, block_force_push, max_file_size, allowed_file_patterns, blocked_file_patterns, connection }) => {
		const body: Record<string, unknown> = {};
		if (require_signed_commits !== undefined) body.require_signed_commits = require_signed_commits;
		if (block_force_push !== undefined) body.block_force_push = block_force_push;
		if (max_file_size !== undefined) body.max_file_size = max_file_size;
		if (allowed_file_patterns !== undefined) body.allowed_file_patterns = allowed_file_patterns;
		if (blocked_file_patterns !== undefined) body.blocked_file_patterns = blocked_file_patterns;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}/push_policy`, body));
	},
);

registerTool(
	'git_org_policy_push_policy_delete',
	'Delete (reset) the push policy for an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/push_policy`)),
);

registerTool(
	'git_org_policy_email_domain_policy_get',
	'Get the email domain policy for an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/email_domain_policy`)),
);

registerTool(
	'git_org_policy_email_domain_policy_edit',
	'Edit the email domain policy for an organization',
	{
		org: z.string().describe('Organization name'),
		allowed_domains: z.array(z.string()).optional().describe('Email domains allowed for members (e.g. ["example.com"])'),
		blocked_domains: z.array(z.string()).optional().describe('Email domains blocked for members'),
		enforce: z.boolean().optional().describe('Enforce the email domain policy'),
		...ConnectionParam,
	},
	async ({ org, allowed_domains, blocked_domains, enforce, connection }) => {
		const body: Record<string, unknown> = {};
		if (allowed_domains !== undefined) body.allowed_domains = allowed_domains;
		if (blocked_domains !== undefined) body.blocked_domains = blocked_domains;
		if (enforce !== undefined) body.enforce = enforce;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}/email_domain_policy`, body));
	},
);

registerTool(
	'git_org_policy_email_domain_policy_delete',
	'Delete (reset) the email domain policy for an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/email_domain_policy`)),
);

registerTool(
	'git_org_policy_repo_defaults_get',
	'Get the repository defaults policy for an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/repo_defaults`)),
);

registerTool(
	'git_org_policy_repo_defaults_edit',
	'Edit the repository defaults policy for an organization',
	{
		org: z.string().describe('Organization name'),
		default_branch: z.string().optional().describe('Default branch for new repositories'),
		private: z.boolean().optional().describe('Create new repositories as private by default'),
		has_issues: z.boolean().optional().describe('Enable issues by default'),
		has_wiki: z.boolean().optional().describe('Enable wiki by default'),
		has_pull_requests: z.boolean().optional().describe('Enable pull requests by default'),
		has_projects: z.boolean().optional().describe('Enable projects by default'),
		default_merge_style: z.string().optional().describe('Default merge style (e.g. "merge", "rebase", "squash")'),
		default_delete_branch_after_merge: z.boolean().optional().describe('Delete branch after merge by default'),
		...ConnectionParam,
	},
	async ({ org, default_branch, private: priv, has_issues, has_wiki, has_pull_requests, has_projects, default_merge_style, default_delete_branch_after_merge, connection }) => {
		const body: Record<string, unknown> = {};
		if (default_branch !== undefined) body.default_branch = default_branch;
		if (priv !== undefined) body.private = priv;
		if (has_issues !== undefined) body.has_issues = has_issues;
		if (has_wiki !== undefined) body.has_wiki = has_wiki;
		if (has_pull_requests !== undefined) body.has_pull_requests = has_pull_requests;
		if (has_projects !== undefined) body.has_projects = has_projects;
		if (default_merge_style !== undefined) body.default_merge_style = default_merge_style;
		if (default_delete_branch_after_merge !== undefined) body.default_delete_branch_after_merge = default_delete_branch_after_merge;
		return formatResponse(await clientFor(connection).patch(`/orgs/${enc(org)}/repo_defaults`, body));
	},
);

registerTool(
	'git_org_policy_repo_defaults_delete',
	'Delete (reset) the repository defaults policy for an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/repo_defaults`)),
);

registerTool(
	'git_org_governance_issue_status_presets_list',
	'List available issue status presets for an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientV2For(connection).get(`/orgs/${enc(org)}/issue-statuses/presets`)),
);

registerTool(
	'git_org_governance_issue_status_preset_apply',
	'Apply an issue status preset to an organization',
	{
		org: z.string().describe('Organization name'),
		preset: z.string().describe('Preset name to apply'),
		...ConnectionParam,
	},
	async ({ org, preset, connection }) => formatResponse(await clientV2For(connection).post(`/orgs/${enc(org)}/issue-statuses/presets/${preset}`, {})),
);

registerTool(
	'git_org_governance_issue_statuses_copy',
	'Copy issue statuses from a source organization into this organization',
	{
		org: z.string().describe('Destination organization name'),
		source_org: z.string().describe('Source organization to copy issue statuses from'),
		...ConnectionParam,
	},
	async ({ org, source_org, connection }) => formatResponse(await clientV2For(connection).post(`/orgs/${enc(org)}/issue-statuses/copy/${enc(source_org)}`, {})),
);

registerTool(
	'git_org_governance_repos_delete',
	'Delete all repositories in an organization',
	{
		org: z.string().describe('Organization name'),
		...ConnectionParam,
	},
	async ({ org, connection }) => formatResponse(await clientFor(connection).delete(`/orgs/${enc(org)}/repos`)),
);

// ── Activity Feeds & Heatmap ──────────────────────────────

registerTool(
	'git_user_activity_feeds',
	'List a user\'s activity feed (userListActivityFeeds — GET /users/{username}/activities/feeds)',
	{
		username: z.string().describe('Username whose activity feed to list'),
		only_performed_by: z.boolean().optional().describe('Only show actions performed by the requested user'),
		date: z.string().optional().describe('Only show activities on or after this date (YYYY-MM-DD)'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ username, only_performed_by, date, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (only_performed_by !== undefined) params['only-performed-by'] = String(only_performed_by);
		if (date) params['date'] = date;
		return formatResponse(await clientFor(connection).get(`/users/${enc(username)}/activities/feeds`, params));
	},
);

registerTool(
	'git_repo_activity_feeds',
	'List a repository\'s activity feed (repoListActivityFeeds — GET /repos/{owner}/{repo}/activities/feeds)',
	{
		...OwnerRepo,
		date: z.string().optional().describe('Only show activities on or after this date (YYYY-MM-DD)'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, date, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (date) params['date'] = date;
		return formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/activities/feeds`, params));
	},
);

registerTool(
	'git_org_activity_feeds',
	'List an organization\'s activity feed (orgListActivityFeeds — GET /orgs/{org}/activities/feeds)',
	{
		org: z.string().describe('Organization name whose activity feed to list'),
		date: z.string().optional().describe('Only show activities on or after this date (YYYY-MM-DD)'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ org, date, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (date) params['date'] = date;
		return formatResponse(await clientFor(connection).get(`/orgs/${enc(org)}/activities/feeds`, params));
	},
);

registerTool(
	'git_user_heatmap',
	'Get a user\'s contribution heatmap data (userGetHeatmapData — GET /users/{username}/heatmap)',
	{
		username: z.string().describe('Username whose contribution heatmap to fetch'),
		...ConnectionParam,
	},
	async ({ username, connection }) => formatResponse(await clientFor(connection).get(`/users/${enc(username)}/heatmap`)),
);

// ── Admin User Management ──────────────────────────────

registerTool(
	'git_admin_user_create',
	'Create a new user (admin only)',
	{
		username: z.string().describe('Username for the new account'),
		email: z.string().describe('Email address'),
		password: z.string().optional().describe('Password (omit to send a randomly-generated one if must_change_password is set)'),
		full_name: z.string().optional().describe('Full display name'),
		login_name: z.string().optional().describe('Login name for external auth sources'),
		source_id: z.number().optional().describe('Authentication source ID (0 for local)'),
		must_change_password: z.boolean().optional().describe('Force password change on first login (default true)'),
		send_notify: z.boolean().optional().describe('Send a notification email to the new user'),
		restricted: z.boolean().optional().describe('Create as a restricted user'),
		visibility: z.enum(['public', 'limited', 'private']).optional().describe('Account visibility'),
		created_at: z.string().optional().describe('Creation timestamp (ISO 8601)'),
		...ConnectionParam,
	},
	async ({ username, email, password, full_name, login_name, source_id, must_change_password, send_notify, restricted, visibility, created_at, connection }) => {
		const body: Record<string, unknown> = { username, email };
		if (password !== undefined) body.password = password;
		if (full_name !== undefined) body.full_name = full_name;
		if (login_name !== undefined) body.login_name = login_name;
		if (source_id !== undefined) body.source_id = source_id;
		if (must_change_password !== undefined) body.must_change_password = must_change_password;
		if (send_notify !== undefined) body.send_notify = send_notify;
		if (restricted !== undefined) body.restricted = restricted;
		if (visibility !== undefined) body.visibility = visibility;
		if (created_at !== undefined) body.created_at = created_at;
		return formatResponse(await clientFor(connection).post('/admin/users', body));
	},
);

registerTool(
	'git_admin_user_edit',
	'Edit an existing user (admin only)',
	{
		username: z.string().describe('Username of the account to edit'),
		email: z.string().optional().describe('New email address'),
		password: z.string().optional().describe('New password'),
		full_name: z.string().optional().describe('New full display name'),
		login_name: z.string().optional().describe('Login name (required by the API for external auth updates)'),
		source_id: z.number().optional().describe('Authentication source ID'),
		must_change_password: z.boolean().optional().describe('Force password change on next login'),
		active: z.boolean().optional().describe('Activate/deactivate the account'),
		admin: z.boolean().optional().describe('Grant/revoke site administrator privileges'),
		restricted: z.boolean().optional().describe('Set restricted status'),
		prohibit_login: z.boolean().optional().describe('Prohibit the user from logging in'),
		allow_git_hook: z.boolean().optional().describe('Allow the user to manage git hooks'),
		allow_import_local: z.boolean().optional().describe('Allow importing local repositories'),
		allow_create_organization: z.boolean().optional().describe('Allow creating organizations'),
		max_repo_creation: z.number().optional().describe('Maximum number of repositories the user may create (-1 for unlimited)'),
		visibility: z.enum(['public', 'limited', 'private']).optional().describe('Account visibility'),
		website: z.string().optional().describe('Website URL'),
		location: z.string().optional().describe('Location'),
		description: z.string().optional().describe('Profile description/bio'),
		...ConnectionParam,
	},
	async ({ username, email, password, full_name, login_name, source_id, must_change_password, active, admin, restricted, prohibit_login, allow_git_hook, allow_import_local, allow_create_organization, max_repo_creation, visibility, website, location, description, connection }) => {
		const body: Record<string, unknown> = {};
		if (email !== undefined) body.email = email;
		if (password !== undefined) body.password = password;
		if (full_name !== undefined) body.full_name = full_name;
		if (login_name !== undefined) body.login_name = login_name;
		if (source_id !== undefined) body.source_id = source_id;
		if (must_change_password !== undefined) body.must_change_password = must_change_password;
		if (active !== undefined) body.active = active;
		if (admin !== undefined) body.admin = admin;
		if (restricted !== undefined) body.restricted = restricted;
		if (prohibit_login !== undefined) body.prohibit_login = prohibit_login;
		if (allow_git_hook !== undefined) body.allow_git_hook = allow_git_hook;
		if (allow_import_local !== undefined) body.allow_import_local = allow_import_local;
		if (allow_create_organization !== undefined) body.allow_create_organization = allow_create_organization;
		if (max_repo_creation !== undefined) body.max_repo_creation = max_repo_creation;
		if (visibility !== undefined) body.visibility = visibility;
		if (website !== undefined) body.website = website;
		if (location !== undefined) body.location = location;
		if (description !== undefined) body.description = description;
		return formatResponse(await clientFor(connection).patch(`/admin/users/${enc(username)}`, body));
	},
);

registerTool(
	'git_admin_user_delete',
	'Delete a user (admin only)',
	{
		username: z.string().describe('Username of the account to delete'),
		purge: z.boolean().optional().describe('Purge the user and all their repositories, even if they still own some'),
		...ConnectionParam,
	},
	async ({ username, purge, connection }) => {
		const path = purge !== undefined ? `/admin/users/${enc(username)}?purge=${String(purge)}` : `/admin/users/${enc(username)}`;
		return formatResponse(await clientFor(connection).delete(path));
	},
);

registerTool(
	'git_admin_user_rename',
	'Rename a user (admin only)',
	{
		username: z.string().describe('Current username of the account'),
		new_username: z.string().describe('New username'),
		...ConnectionParam,
	},
	async ({ username, new_username, connection }) => {
		return formatResponse(await clientFor(connection).post(`/admin/users/${enc(username)}/rename`, { new_username }));
	},
);

registerTool(
	'git_admin_user_key_create',
	'Add a public SSH key on behalf of a user (admin only)',
	{
		username: z.string().describe('Username to add the key for'),
		key: z.string().describe('Public key content (e.g. "ssh-ed25519 AAAA...")'),
		title: z.string().describe('Title/label for the key'),
		read_only: z.boolean().optional().describe('Mark the key as read-only'),
		...ConnectionParam,
	},
	async ({ username, key, title, read_only, connection }) => {
		const body: Record<string, unknown> = { key, title };
		if (read_only !== undefined) body.read_only = read_only;
		return formatResponse(await clientFor(connection).post(`/admin/users/${enc(username)}/keys`, body));
	},
);

registerTool(
	'git_admin_user_key_delete',
	'Delete a public key belonging to a user (admin only)',
	{
		username: z.string().describe('Username that owns the key'),
		id: z.number().describe('Public key ID to delete'),
		...ConnectionParam,
	},
	async ({ username, id, connection }) => formatResponse(await clientFor(connection).delete(`/admin/users/${enc(username)}/keys/${enc(id)}`)),
);

registerTool(
	'git_admin_user_badges_list',
	'List badges assigned to a user (admin only)',
	{
		username: z.string().describe('Username whose badges to list'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ username, page, limit, connection }) => formatResponse(await clientFor(connection).get(`/admin/users/${enc(username)}/badges`, pageQuery({ page, limit }))),
);

registerTool(
	'git_admin_user_badges_add',
	'Add badges to a user (admin only)',
	{
		username: z.string().describe('Username to add badges to'),
		badges: z.array(z.string()).describe('List of badge slugs to add'),
		...ConnectionParam,
	},
	async ({ username, badges, connection }) => formatResponse(await clientFor(connection).post(`/admin/users/${enc(username)}/badges`, { badges })),
);

registerTool(
	'git_admin_user_badges_delete',
	'Remove badges from a user (admin only)',
	{
		username: z.string().describe('Username to remove badges from'),
		badges: z.array(z.string()).describe('List of badge slugs to remove'),
		...ConnectionParam,
	},
	async ({ username, badges, connection }) => formatResponse(await clientFor(connection).delete(`/admin/users/${enc(username)}/badges`, { badges })),
);

registerTool(
	'git_admin_emails_list',
	'List all email addresses across all users (admin only)',
	{
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/admin/emails', pageQuery({ page, limit }))),
);

registerTool(
	'git_admin_emails_search',
	'Search email addresses across all users (admin only)',
	{
		q: z.string().optional().describe('Search query to match against email addresses'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ q, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (q !== undefined) params['q'] = q;
		return formatResponse(await clientFor(connection).get('/admin/emails/search', params));
	},
);

// ── Admin Org / Repo Management ──────────────────────────────

registerTool(
	'git_admin_org_create',
	'Create an organization owned by a user (admin only)',
	{
		username: z.string().describe('Username of the user who will own the new organization'),
		org_name: z.string().describe('Name for the new organization'),
		full_name: z.string().optional().describe('Full display name of the organization'),
		description: z.string().optional().describe('Organization description'),
		website: z.string().optional().describe('Organization website URL'),
		location: z.string().optional().describe('Organization location'),
		visibility: z.enum(['public', 'limited', 'private']).optional().describe('Organization visibility'),
		repo_admin_change_team_access: z.boolean().optional().describe('Allow repo admins to change team access'),
		...ConnectionParam,
	},
	async ({ username, org_name, full_name, description, website, location, visibility, repo_admin_change_team_access, connection }) => {
		const body: Record<string, unknown> = { username: org_name };
		if (full_name !== undefined) body.full_name = full_name;
		if (description !== undefined) body.description = description;
		if (website !== undefined) body.website = website;
		if (location !== undefined) body.location = location;
		if (visibility !== undefined) body.visibility = visibility;
		if (repo_admin_change_team_access !== undefined) body.repo_admin_change_team_access = repo_admin_change_team_access;
		return formatResponse(await clientFor(connection).post(`/admin/users/${enc(username)}/orgs`, body));
	},
);

registerTool(
	'git_admin_repo_create',
	'Create a repository owned by a user (admin only)',
	{
		username: z.string().describe('Username of the user who will own the new repository'),
		name: z.string().describe('Name for the new repository'),
		description: z.string().optional().describe('Repository description'),
		private: z.boolean().optional().describe('Make the repository private'),
		auto_init: z.boolean().optional().describe('Initialize with README'),
		default_branch: z.string().optional().describe('Default branch (default "main")'),
		gitignores: z.string().optional().describe('Gitignore template(s) to use'),
		license: z.string().optional().describe('License template to use'),
		readme: z.string().optional().describe('Readme template to use'),
		template: z.boolean().optional().describe('Mark as template repository'),
		trust_model: z.enum(['default', 'collaborator', 'committer', 'collaboratorcommitter']).optional().describe('Trust model for repository signatures'),
		...ConnectionParam,
	},
	async ({ username, name, description, private: priv, auto_init, default_branch, gitignores, license, readme, template: tmpl, trust_model, connection }) => {
		const body: Record<string, unknown> = { name };
		if (description !== undefined) body.description = description;
		if (priv !== undefined) body.private = priv;
		if (auto_init !== undefined) body.auto_init = auto_init;
		if (default_branch !== undefined) body.default_branch = default_branch;
		if (gitignores !== undefined) body.gitignores = gitignores;
		if (license !== undefined) body.license = license;
		if (readme !== undefined) body.readme = readme;
		if (tmpl !== undefined) body.template = tmpl;
		if (trust_model !== undefined) body.trust_model = trust_model;
		return formatResponse(await clientFor(connection).post(`/admin/users/${enc(username)}/repos`, body));
	},
);

registerTool(
	'git_admin_unadopted_list',
	'List unadopted repositories (present on disk but not registered, admin only)',
	{
		pattern: z.string().optional().describe('Pattern to match against unadopted repository names'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ pattern, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (pattern !== undefined) params['pattern'] = pattern;
		return formatResponse(await clientFor(connection).get('/admin/unadopted', params));
	},
);

registerTool(
	'git_admin_repo_adopt',
	'Adopt an unadopted repository (register on-disk files as a repository, admin only)',
	{
		owner: z.string().describe('Owner (user or org) of the unadopted repository'),
		repo: z.string().describe('Name of the unadopted repository'),
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).post(`/admin/unadopted/${enc(owner)}/${enc(repo)}`, {})),
);

registerTool(
	'git_admin_unadopted_delete',
	'Delete the on-disk files of an unadopted repository (admin only)',
	{
		owner: z.string().describe('Owner (user or org) of the unadopted repository'),
		repo: z.string().describe('Name of the unadopted repository'),
		...ConnectionParam,
	},
	async ({ owner, repo, connection }) => formatResponse(await clientFor(connection).delete(`/admin/unadopted/${enc(owner)}/${enc(repo)}`)),
);

// ── Admin Workflow Runs & Jobs ──────────────────────────────

registerTool(
	'git_admin_workflow_runs_list',
	'List all Actions workflow runs across the instance (admin scope)',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/admin/actions/runs', pageQuery({ page, limit }))),
);

registerTool(
	'git_admin_workflow_jobs_list',
	'List all Actions workflow jobs across the instance (admin scope)',
	{ ...PaginationParams, ...ConnectionParam },
	async ({ page, limit, connection }) => formatResponse(await clientFor(connection).get('/admin/actions/jobs', pageQuery({ page, limit }))),
);

// ── Notifications (thread & per-repo) ──────────────────────────────

registerTool(
	'git_notification_thread_get',
	'Get a single notification thread by ID',
	{
		thread_id: z.string().describe('Notification thread ID'),
		...ConnectionParam,
	},
	async ({ thread_id, connection }) => formatResponse(await clientFor(connection).get(`/notifications/threads/${enc(thread_id)}`)),
);

registerTool(
	'git_notification_thread_read',
	'Mark a notification thread as read (or set another status via to_status)',
	{
		thread_id: z.string().describe('Notification thread ID'),
		to_status: z.string().optional().describe('Target status to set (e.g. read, unread, pinned; default: read)'),
		...ConnectionParam,
	},
	async ({ thread_id, to_status, connection }) => {
		const qs = to_status ? `?to-status=${encodeURIComponent(to_status)}` : '';
		return formatResponse(await clientFor(connection).patch(`/notifications/threads/${enc(thread_id)}${qs}`, {}));
	},
);

registerTool(
	'git_notifications_new_count',
	'Check whether the authenticated user has any new (unread) notifications',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/notifications/new')),
);

registerTool(
	'git_repo_notifications_list',
	'List notifications for the authenticated user within a specific repository',
	{
		...OwnerRepo,
		status_types: z.string().optional().describe('Comma-separated status filter: read, unread, pinned'),
		...PaginationParams,
		...ConnectionParam,
	},
	async ({ owner, repo, status_types, page, limit, connection }) => {
		const params: Record<string, string> = { ...pageQuery({ page, limit }) };
		if (status_types) params['status-types'] = status_types;
		return formatResponse(await clientFor(connection).get(`/repos/${enc(owner)}/${enc(repo)}/notifications`, params));
	},
);

registerTool(
	'git_repo_notifications_read',
	'Mark all notifications within a specific repository as read (or set another status via to_status)',
	{
		...OwnerRepo,
		to_status: z.string().optional().describe('Target status to set (e.g. read, unread, pinned; default: read)'),
		last_read_at: z.string().optional().describe('Only mark notifications updated before this time as read (ISO 8601)'),
		...ConnectionParam,
	},
	async ({ owner, repo, to_status, last_read_at, connection }) => {
		const q = new URLSearchParams();
		if (to_status) q.set('to-status', to_status);
		if (last_read_at) q.set('last_read_at', last_read_at);
		const qs = q.toString() ? `?${q.toString()}` : '';
		return formatResponse(await clientFor(connection).put(`/repos/${enc(owner)}/${enc(repo)}/notifications${qs}`, {}));
	},
);

// ── Templates & Markdown Rendering ──────────────────────────────

registerTool(
	'git_gitignore_templates_list',
	'List all available .gitignore templates',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/gitignore/templates')),
);

registerTool(
	'git_gitignore_template_get',
	'Get info (name and source) for a specific .gitignore template',
	{
		name: z.string().describe('Template name (e.g. "Node", "Go", "Python")'),
		...ConnectionParam,
	},
	async ({ name, connection }) => formatResponse(await clientFor(connection).get(`/gitignore/templates/${enc(name)}`)),
);

registerTool(
	'git_label_templates_list',
	'List all available label templates',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/label/templates')),
);

registerTool(
	'git_label_template_get',
	'Get the labels defined in a specific label template',
	{
		name: z.string().describe('Label template name (e.g. "Default", "Advanced")'),
		...ConnectionParam,
	},
	async ({ name, connection }) => formatResponse(await clientFor(connection).get(`/label/templates/${enc(name)}`)),
);

registerTool(
	'git_license_templates_list',
	'List all available license templates',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get('/licenses')),
);

registerTool(
	'git_license_template_get',
	'Get info and full text for a specific license template',
	{
		name: z.string().describe('License template name (e.g. "MIT", "GPL-3.0-or-later", "Apache-2.0")'),
		...ConnectionParam,
	},
	async ({ name, connection }) => formatResponse(await clientFor(connection).get(`/licenses/${enc(name)}`)),
);

registerTool(
	'git_markdown_render',
	'Render a Markdown document to HTML',
	{
		text: z.string().describe('Markdown text to render'),
		mode: z.enum(['gfm', 'markdown', 'comment', 'wiki']).optional().describe('Rendering mode (default: markdown)'),
		context: z.string().optional().describe('Repository context in "owner/repo" form for resolving relative links and references'),
		wiki: z.boolean().optional().describe('Render as a wiki page'),
		...ConnectionParam,
	},
	async ({ text, mode, context, wiki, connection }) => {
		const body: Record<string, unknown> = { Text: text };
		if (mode) body.Mode = mode;
		if (context) body.Context = context;
		if (wiki !== undefined) body.Wiki = wiki;
		return formatResponse(await clientFor(connection).post('/markdown', body));
	},
);

registerTool(
	'git_markdown_render_raw',
	'Render raw Markdown text to HTML (plain text body, no context resolution)',
	{
		text: z.string().describe('Raw Markdown text to render'),
		...ConnectionParam,
	},
	async ({ text, connection }) => formatResponse(await clientFor(connection).post('/markdown/raw', text)),
);

registerTool(
	'git_markup_render',
	'Render arbitrary markup (markdown, org-mode, etc.) to HTML',
	{
		text: z.string().describe('Markup text to render'),
		mode: z.enum(['gfm', 'markdown', 'comment', 'wiki', 'file']).optional().describe('Markup rendering mode (default: markdown)'),
		context: z.string().optional().describe('Repository context in "owner/repo" form for resolving relative links and references'),
		wiki: z.boolean().optional().describe('Render as a wiki page'),
		file_path: z.string().optional().describe('File path used to detect the markup format when mode is "file"'),
		...ConnectionParam,
	},
	async ({ text, mode, context, wiki, file_path, connection }) => {
		const body: Record<string, unknown> = { Text: text };
		if (mode) body.Mode = mode;
		if (context) body.Context = context;
		if (wiki !== undefined) body.Wiki = wiki;
		if (file_path) body.FilePath = file_path;
		return formatResponse(await clientFor(connection).post('/markup', body));
	},
);

registerTool(
	'git_signing_key_get',
	'Get the default GPG signing key for the instance (ASCII-armored public key)',
	{ ...ConnectionParam },
	async ({ connection }) => {
		const res = await clientFor(connection).get('/signing-key.gpg');
		if (res.status >= 400) return formatResponse(res);
		const text = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
		return { content: [{ type: 'text' as const, text }] };
	},
);

registerTool(
	'git_signing_key_ssh_get',
	'Get the default SSH signing key for the instance',
	{ ...ConnectionParam },
	async ({ connection }) => {
		const res = await clientFor(connection).get('/signing-key.pub');
		if (res.status >= 400) return formatResponse(res);
		const text = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
		return { content: [{ type: 'text' as const, text }] };
	},
);

// ── Instance Settings ──────────────────────────────

registerTool(
	'git_settings_api_get',
	'Get the instance general API settings (e.g. max response items, default/max paging sizes)',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get(`/settings/api`)),
);

registerTool(
	'git_settings_attachment_get',
	'Get the instance general attachment settings (allowed types, max size, max files, enabled)',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get(`/settings/attachment`)),
);

registerTool(
	'git_settings_repository_get',
	'Get the instance general repository settings (e.g. mirrors enabled, HTTP git enabled, forks disabled)',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get(`/settings/repository`)),
);

registerTool(
	'git_settings_ui_get',
	'Get the instance general UI settings (e.g. default theme, allowed reactions, custom emojis)',
	{ ...ConnectionParam },
	async ({ connection }) => formatResponse(await clientFor(connection).get(`/settings/ui`)),
);

// ── Sync-profile apply (poll-to-completion wrapper) ──────────────────────
//
// mokogit-mcp #237 — the generated git_org_sync_profile_apply fired the POST
// .../sync-profiles/{id}/sync ONCE and returned. On a large profile (79
// targets, 209 pending changes) the server processes in BATCHES: a single
// apply call only advances part way (observed 209→54), so the operator had to
// manually re-invoke apply and watch git_org_sync_profile_status until it hit
// 0. Worse, a big batch can exceed the client's 30s TIMEOUT_MS: the HTTP
// response times out while the server KEEPS applying in the background, which
// surfaces to the caller as a hard failure even though progress is being made.
//
// This hand-written tool SHADOWS the generated one (registered before
// registerGeneratedToolsV2(), so the collision guard skips the generated name)
// and POLLS to completion: apply → status → (if still drifting) apply again,
// until in_sync, a stall (pending stops dropping across 2 rounds), or a safety
// cap. An apply timeout is treated as "still running" — we swallow it and poll
// status to observe real progress rather than failing the whole operation.
//
// wait:true (DEFAULT) = the new polling behavior; wait:false = the historical
// single-shot apply (one POST, formatted response) for callers that want it.

interface SyncStatus {
	target_count?: number;
	pending_changes?: number;
	in_sync?: boolean;
}

// Pull {pending_changes, in_sync, target_count} out of a status response,
// tolerating either a bare object or a {data:{…}} / {status:{…}} wrapper.
function parseSyncStatus(data: unknown): SyncStatus {
	let obj: Record<string, unknown> | undefined;
	if (data && typeof data === 'object') {
		const d = data as Record<string, unknown>;
		if (d.status && typeof d.status === 'object') obj = d.status as Record<string, unknown>;
		else if (d.data && typeof d.data === 'object') obj = d.data as Record<string, unknown>;
		else obj = d;
	}
	if (!obj) return {};
	const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined);
	return {
		target_count: num(obj.target_count),
		pending_changes: num(obj.pending_changes),
		in_sync: typeof obj.in_sync === 'boolean' ? (obj.in_sync as boolean) : undefined,
	};
}

// Collect the target_repo_id of every applied entry in an apply response's
// results[] (tolerating a {data:{results}} / {results} / bare-array shape).
function collectAppliedIds(data: unknown, into: Set<number>): void {
	let results: unknown;
	if (Array.isArray(data)) {
		results = data;
	} else if (data && typeof data === 'object') {
		const d = data as Record<string, unknown>;
		if (Array.isArray(d.results)) results = d.results;
		else if (d.data && typeof d.data === 'object') {
			const inner = (d.data as Record<string, unknown>).results;
			if (Array.isArray(inner)) results = inner;
		}
	}
	if (!Array.isArray(results)) return;
	for (const r of results) {
		if (r && typeof r === 'object') {
			const entry = r as { target_repo_id?: unknown; applied?: unknown };
			if (entry.applied === true && typeof entry.target_repo_id === 'number') {
				into.add(entry.target_repo_id);
			}
		}
	}
}

const SYNC_APPLY_MAX_ROUNDS = 10;

registerTool(
	'git_org_sync_profile_apply',
	'Apply a sync profile to its member repos, committing where changed. By default (wait=true) this POLLS to completion: the server applies in batches, so this re-invokes apply and checks status until the profile is in sync, progress stalls, or a safety cap of 10 rounds is hit — an HTTP timeout on an apply round is treated as "still running" (the server keeps working) and the loop continues by polling status. Returns the per-round pending-change trajectory, round count, final {in_sync, pending_changes}, and the merged set of applied target_repo_ids. Set wait=false for a single-shot apply (the old one-POST behavior).',
	{
		org: z.string().describe('name of the organization'),
		id: z.number().describe('id of the sync profile'),
		wait: z
			.boolean()
			.optional()
			.describe('Poll to completion (default true). false = single-shot apply (one POST, no polling).'),
		body: z.record(z.string(), z.unknown()).optional().describe('Request body (JSON object matching the API schema)'),
		...ConnectionParam,
	},
	async ({ org, id, wait, body, connection }, extra) => {
		const client = clientFor(connection);
		const o = encodeURIComponent(String(org));
		const i = encodeURIComponent(String(id));
		const applyEndpoint = `/orgs/${o}/sync-profiles/${i}/sync`;
		const statusEndpoint = `/orgs/${o}/sync-profiles/${i}/status`;

		// wait=false → historical single-shot behavior.
		if (wait === false) {
			return formatResponse(await client.post(applyEndpoint, body ?? {}));
		}

		const trajectory: Array<number | null> = []; // pending_changes observed per round (null = unknown)
		const appliedIds = new Set<number>();
		let rounds = 0;
		let lastStatus: SyncStatus = {};
		let stopReason: 'in_sync' | 'stall' | 'cap' | 'error' = 'cap';
		let timeoutsObserved = 0;
		let fatalError: string | null = null;
		let prevPending: number | null = null;
		let stalledRounds = 0;

		const isTimeout = (err: unknown): boolean =>
			err instanceof Error && /timed out|timeout|ETIMEDOUT|ESOCKETTIMEDOUT/i.test(err.message);

		for (rounds = 1; rounds <= SYNC_APPLY_MAX_ROUNDS; rounds++) {
			// 1) Apply. A timeout here means the server is still applying in the
			//    background — swallow it and fall through to the status poll.
			try {
				const applyRes = await client.post(applyEndpoint, body ?? {});
				if (applyRes.status >= 400) {
					const errObj = applyRes.data as { message?: string };
					fatalError = errObj?.message ?? `HTTP ${applyRes.status}: ${JSON.stringify(applyRes.data)}`;
					stopReason = 'error';
					break;
				}
				collectAppliedIds(applyRes.data, appliedIds);
			} catch (err) {
				if (isTimeout(err)) {
					timeoutsObserved++;
				} else {
					fatalError = err instanceof Error ? err.message : String(err);
					stopReason = 'error';
					break;
				}
			}

			// 2) Status. A status timeout is non-fatal: record unknown and keep going.
			try {
				const statusRes = await client.get(statusEndpoint);
				if (statusRes.status >= 400) {
					const errObj = statusRes.data as { message?: string };
					fatalError = errObj?.message ?? `HTTP ${statusRes.status}: ${JSON.stringify(statusRes.data)}`;
					stopReason = 'error';
					break;
				}
				lastStatus = parseSyncStatus(statusRes.data);
			} catch (err) {
				if (isTimeout(err)) {
					timeoutsObserved++;
					lastStatus = {};
				} else {
					fatalError = err instanceof Error ? err.message : String(err);
					stopReason = 'error';
					break;
				}
			}

			const pending = lastStatus.pending_changes ?? null;
			trajectory.push(pending);

			// Best-effort progress notification (never block/fail on it).
			try {
				const send = (extra as { sendNotification?: (n: unknown) => Promise<void> } | undefined)?.sendNotification;
				if (typeof send === 'function') {
					void send({
						method: 'notifications/message',
						params: {
							level: 'info',
							data: `sync apply round ${rounds}: pending ${pending ?? 'unknown'}`,
						},
					}).catch(() => {});
				}
			} catch {
				/* progress is advisory — ignore */
			}

			// 3) Terminal checks.
			if (lastStatus.in_sync === true || pending === 0) {
				stopReason = 'in_sync';
				break;
			}
			if (pending !== null && prevPending !== null) {
				if (pending >= prevPending) {
					stalledRounds++;
					if (stalledRounds >= 2) {
						stopReason = 'stall';
						break;
					}
				} else {
					stalledRounds = 0;
				}
			}
			if (pending !== null) prevPending = pending;
		}
		if (rounds > SYNC_APPLY_MAX_ROUNDS) rounds = SYNC_APPLY_MAX_ROUNDS;

		const finalInSync = lastStatus.in_sync === true || (lastStatus.pending_changes ?? -1) === 0;
		const result = {
			org: String(org),
			profile_id: id,
			waited: true,
			rounds,
			pending_trajectory: trajectory,
			final: {
				in_sync: finalInSync,
				pending_changes: lastStatus.pending_changes ?? null,
				target_count: lastStatus.target_count ?? null,
			},
			applied_target_repo_ids: [...appliedIds].sort((a, b) => a - b),
			stop_reason: stopReason,
			apply_timeouts_observed: timeoutsObserved,
			...(fatalError ? { error: fatalError } : {}),
			note:
				stopReason === 'in_sync'
					? 'Profile reached in_sync.'
					: stopReason === 'stall'
						? `Stopped: pending_changes stopped decreasing (stall) with ${lastStatus.pending_changes ?? 'unknown'} change(s) remaining. The profile is NOT fully in sync — inspect the remaining targets.`
						: stopReason === 'cap'
							? `Stopped: hit the ${SYNC_APPLY_MAX_ROUNDS}-round safety cap with ${lastStatus.pending_changes ?? 'unknown'} change(s) remaining. The profile is NOT fully in sync — re-invoke apply or inspect the remaining targets.`
							: `Stopped on error after ${rounds} round(s); ${lastStatus.pending_changes ?? 'unknown'} change(s) may remain.`,
		};

		return { content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }] };
	},
);

// ── Start Server ────────────────────────────────────────────────────────

async function main(): Promise<void> {
	config = await loadConfig();
	// Opt into the auto-generated V2 tools only. v1 is already fully hand-covered
	// above, so we deliberately do NOT register the generated v1 set (its
	// operationId-derived names would duplicate every v1 endpoint). This adds just
	// the missing v2 surfaces — licensing, security, license-keys/packages,
	// custom-fields, badges, cascade, feature-policies. The generated registration
	// shares this module's config, server, and name registry; its registerTool
	// skips any canonical name already registered above as a safety net, so the
	// hand-written tools (incl. the guardrail wrappers) always win.
	setGeneratedConfig(config);
	setGeneratedServer(server);
	setRegisteredNames(registeredNames);
	registerGeneratedToolsV2();
	// Detect the operation backends (API > mokogit-cli > git) and emit a one-time,
	// non-fatal status line. The REST API is the primary path; mokogit-cli/git are
	// fallbacks. Detection must never block startup, so swallow any probe error.
	try {
		warnBackendStatus(await probeBackends());
	} catch {
		/* detection is best-effort; the server runs API-only regardless */
	}
	const transport = new StdioServerTransport();
	await server.connect(transport);
}

main().catch((err) => {
	process.stderr.write(`Fatal: ${err}\n`);
	process.exit(1);
});
