leejunyoung5819gitgit-mcp

공개

gitgit.kr MCP 도구

GitGit MCP 서버 추가

GitGit REST API(/api/v1)를 Codex, Claude 데스크탑 앱, Claude Code 에서
쓸 수 있게 하는 stdio MCP 서버. 저장소와 코드 탐색, Issue, PR 리뷰와
병합, Release 와 Asset 을 다루는 도구 40개와 api_request 를 제공함.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
작성자
LeeJunyoung
작성 시각
커밋
59afdb6ac8f464214d3a897a3a5ee711faf90186
부모
없음 (첫 커밋)
이 시점의 파일 보기

변경된 파일 17개

+1,437-0
추가.gitignore+3-0
@@ -0,0 +1,3 @@
1추가: node_modules/
2추가: dist/
3추가: *.log
추가README.md+127-0
@@ -0,0 +1,127 @@
1추가: # gitgit-mcp
2추가:
3추가: GitGit(gitgit.kr) REST API(`/api/v1`)를 MCP 도구로 감싼 stdio 서버입니다. Codex, Claude 데스크탑 앱, Claude Code 같은 MCP 클라이언트가 이 서버를 하위 프로세스로 실행하면, AI 에이전트가 GitGit 저장소를 읽고 Issue, PR, 리뷰, 병합, Release 를 다룰 수 있습니다.
4추가:
5추가: - 인증은 계정 설정이나 Bot 설정에서 발급한 액세스 토큰(`ggp_…` 개인, `ggb_…` Bot) 하나만 씁니다. 토큰이 없으면 공개 저장소 읽기만 됩니다.
6추가: - 권한 판정은 모두 서버가 합니다. 토큰의 범위(scope)와 저장소 범위, Bot 의 저장소별 권한, 보호 브랜치 규칙이 그대로 적용됩니다.
7추가: - 코드 변경(커밋, Push)은 API 가 아니라 `git` 으로 합니다. clone 주소는 `get_repository` 가 돌려주는 `sshUrl`/`httpUrl` 입니다.
8추가:
9추가: ## 1. 받기와 빌드
10추가:
11추가: Node.js 22.21 이상이 필요합니다.
12추가:
13추가: ```bash
14추가: git clone https://gitgit.kr/leejunyoung5819/gitgit-mcp.git
15추가: cd gitgit-mcp
16추가: npm ci
17추가: npm run build
18추가: ```
19추가:
20추가: 결과물은 `gitgit-mcp/dist/index.js` 입니다. 동작을 확인하려면 `node dist/index.js --help` 를 실행합니다.
21추가:
22추가: ## 2. 토큰 발급
23추가:
24추가: 웹의 **계정 설정 → 토큰**(Bot 이면 **Bot 설정 → 토큰**)에서 발급합니다. 원문은 발급할 때 한 번만 보입니다.
25추가:
26추가: | 하려는 일 | 필요한 범위 |
27추가: | :---- | :---- |
28추가: | 계정 확인 (`whoami`, `list_organizations`) | `profile:read` |
29추가: | 저장소, 코드, 커밋 읽기 | `repositories:read` |
30추가: | 저장소 만들기 | `repositories:write` (사용자 토큰만) |
31추가: | Issue, 댓글, Label 읽기 / 쓰기 | `issues:read` / `issues:write` |
32추가: | PR, 리뷰 읽기 / 쓰기 | `pulls:read` / `pulls:write` |
33추가: | PR 병합 | `pulls:merge` |
34추가: | Release 읽기 / 쓰기, Asset 업로드 | `releases:read` / `releases:write` |
35추가:
36추가: 에이전트에게 맡길 저장소만 고르는 **선택한 저장소** 범위와 짧은 만료일을 권장합니다. 병합을 맡기지 않으려면 `pulls:merge` 를 빼세요.
37추가:
38추가: ## 3. 환경 변수
39추가:
40추가: | 변수 | 설명 |
41추가: | :---- | :---- |
42추가: | `GITGIT_API_URL` | API 서버 주소. 기본 `https://api.gitgit.kr`, 로컬 개발은 `http://localhost:8080`. `/api/v1` 은 붙여도 되고 빼도 됩니다. |
43추가: | `GITGIT_TOKEN` | 액세스 토큰. 없으면 익명(공개 저장소 읽기만) |
44추가: | `GITGIT_TOKEN_FILE` | 토큰을 담은 파일 경로. 설정 파일에 토큰을 적고 싶지 않을 때 `GITGIT_TOKEN` 대신 씁니다 (`chmod 600` 권장). |
45추가: | `GITGIT_READ_ONLY` | `1` 이면 읽기 도구만 등록하고 `api_request` 도 GET 만 받습니다. |
46추가: | `GITGIT_TIMEOUT_MS` | API 요청 제한 시간 (기본 30000) |
47추가: | `GITGIT_UPLOAD_TIMEOUT_MS` | Asset 업로드 제한 시간 (기본 600000) |
48추가: | `GITGIT_MAX_OUTPUT_CHARS` | 도구 응답 최대 글자 수 (기본 100000). 넘으면 잘라서 돌려줍니다. |
49추가:
50추가: ## 4. 클라이언트에 등록
51추가:
52추가: 아래 예시의 `/path/to/gitgit-mcp` 는 이 저장소를 받은 위치로 바꾸세요. Claude 데스크탑 앱은 로그인 셸의 `PATH` 를 읽지 않으므로 nvm 등으로 설치한 Node 는 `command` 에 **절대 경로**를 적어야 합니다 (`which node` 로 확인).
53추가:
54추가: ### Codex (CLI, IDE 확장, 데스크탑 앱 공통)
55추가:
56추가: 명령으로 등록합니다.
57추가:
58추가: ```bash
59추가: codex mcp add gitgit --env GITGIT_API_URL=https://api.gitgit.kr --env GITGIT_TOKEN_FILE=$HOME/.config/gitgit/token -- node /path/to/gitgit-mcp/dist/index.js
60추가: ```
61추가:
62추가: 또는 `~/.codex/config.toml` 에 직접 적습니다.
63추가:
64추가: ```toml
65추가: [mcp_servers.gitgit]
66추가: command = "node"
67추가: args = ["/path/to/gitgit-mcp/dist/index.js"]
68추가:
69추가: [mcp_servers.gitgit.env]
70추가: GITGIT_API_URL = "https://api.gitgit.kr"
71추가: GITGIT_TOKEN_FILE = "/home/<사용자>/.config/gitgit/token"
72추가: ```
73추가:
74추가: `codex mcp list` 로 등록을 확인하고, Codex 대화에서 `/mcp` 로 도구 목록을 볼 수 있습니다.
75추가:
76추가: ### Claude 데스크탑 앱
77추가:
78추가: **설정 → 개발자 → 설정 편집**으로 `claude_desktop_config.json` 을 엽니다 (Linux `~/.config/Claude/`, macOS `~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`).
79추가:
80추가: ```json
81추가: {
82추가: "mcpServers": {
83추가: "gitgit": {
84추가: "command": "/home/<사용자>/.nvm/versions/node/v24.21.0/bin/node",
85추가: "args": ["/path/to/gitgit-mcp/dist/index.js"],
86추가: "env": {
87추가: "GITGIT_API_URL": "https://api.gitgit.kr",
88추가: "GITGIT_TOKEN_FILE": "/home/<사용자>/.config/gitgit/token"
89추가: }
90추가: }
91추가: }
92추가: }
93추가: ```
94추가:
95추가: 저장한 뒤 앱을 완전히 종료했다가 다시 열면 대화 입력창의 도구 메뉴에 `gitgit` 이 나타납니다. 연결이 안 되면 `~/.config/Claude/logs/` 의 `mcp.log`, `mcp-server-gitgit.log` 를 확인하세요. 서버는 시작할 때 접속 주소와 인증 여부를 stderr 에 한 줄 남깁니다.
96추가:
97추가: ### Claude Code
98추가:
99추가: ```bash
100추가: claude mcp add gitgit -e GITGIT_API_URL=https://api.gitgit.kr -e GITGIT_TOKEN_FILE=$HOME/.config/gitgit/token -- node /path/to/gitgit-mcp/dist/index.js
101추가: ```
102추가:
103추가: ## 5. 도구 목록
104추가:
105추가: 읽기 도구는 `readOnlyHint`, 병합과 삭제는 `destructiveHint` 가 붙어 있어 클라이언트가 실행 전에 확인을 받을 수 있습니다.
106추가:
107추가: | 분류 | 도구 |
108추가: | :---- | :---- |
109추가: | 계정, 탐색 | `whoami`, `search`, `list_repositories`, `list_organizations`, `get_repository`, `create_repository` |
110추가: | 코드 | `list_tree`, `read_file`(줄 범위, 줄 번호), `list_branches`, `list_tags`, `list_commits`, `get_commit`, `search_repository`, `compare_branches` |
111추가: | Issue | `list_issues`, `get_issue`(댓글 포함), `list_issue_comments`, `list_labels`, `create_issue`, `update_issue`, `create_issue_comment` |
112추가: | PR | `list_pulls`, `get_pull`(base/head OID, 변경 파일), `get_pull_diff`, `list_pull_commits`, `list_pull_comments`, `list_pull_reviews`, `create_pull`, `update_pull`, `create_pull_comment`(줄 댓글), `submit_pull_review`, `merge_pull` |
113추가: | Release | `list_releases`, `get_release`(id, 태그, 최신), `create_release`, `update_release`, `delete_release`, `upload_release_asset`, `delete_release_asset` |
114추가: | 기타 | `api_request` — 전용 도구가 없는 `/api/v1` 경로 직접 호출 (예: Label 만들기, 보호 브랜치 조회) |
115추가:
116추가: - `merge_pull` 은 `get_pull` 로 확인한 `baseOid`/`headOid` 를 `expectedBaseOid`/`expectedHeadOid` 로 넘겨야 합니다. 그 사이 브랜치가 바뀌면 서버가 병합을 거부하므로, 에이전트가 보지 않은 변경이 병합되지 않습니다.
117추가: - `submit_pull_review`, `create_pull_comment` 는 커밋 OID 를 생략하면 현재 head 커밋을 씁니다.
118추가: - `upload_release_asset` 은 MCP 서버가 실행 중인 컴퓨터의 파일을 올립니다.
119추가: - 웹 세션 전용 API(알림, 계정 보안, 토큰과 Bot 관리, 관리자 API)는 토큰으로 부를 수 없어 `TOKEN_NOT_ALLOWED` 로 거부됩니다.
120추가:
121추가: ## 6. 테스트
122추가:
123추가: ```bash
124추가: npm test
125추가: ```
126추가:
127추가: 모형 HTTP 서버를 API 자리에 두고 MCP 서버를 실제 stdio 하위 프로세스로 띄워, 도구가 올바른 경로, 쿼리, 본문, 인증 헤더로 API 를 부르는지와 읽기 전용 모드, 오류 변환, 경로 제한을 확인합니다.
추가package-lock.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가package.json+31-0
@@ -0,0 +1,31 @@
1추가: {
2추가: "name": "gitgit-mcp",
3추가: "version": "0.1.0",
4추가: "private": true,
5추가: "description": "GitGit(gitgit.kr) REST API를 Codex, Claude 데스크탑 앱 같은 MCP 클라이언트에서 쓰게 해 주는 stdio MCP 서버",
6추가: "type": "module",
7추가: "engines": {
8추가: "node": ">=22.21.0"
9추가: },
10추가: "bin": {
11추가: "gitgit-mcp": "dist/index.js"
12추가: },
13추가: "files": [
14추가: "dist"
15추가: ],
16추가: "scripts": {
17추가: "build": "tsc",
18추가: "typecheck": "tsc --noEmit",
19추가: "start": "node dist/index.js",
20추가: "dev": "node --experimental-strip-types --disable-warning=ExperimentalWarning src/index.ts",
21추가: "test": "npm run build && node --test test/*.test.mjs"
22추가: },
23추가: "dependencies": {
24추가: "@modelcontextprotocol/sdk": "1.32.2",
25추가: "zod": "4.6.7"
26추가: },
27추가: "devDependencies": {
28추가: "@types/node": "22.20.5",
29추가: "typescript": "5.9.3"
30추가: }
31추가: }
추가src/client.ts+129-0
@@ -0,0 +1,129 @@
1추가: import type { Config } from "./config.ts";
2추가: import { version } from "./config.ts";
3추가:
4추가: export type QueryValue = string | number | boolean | undefined | null;
5추가: export type Query = Record<string, QueryValue>;
6추가: export type Method = "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
7추가:
8추가: export type RequestOptions = {
9추가: query?: Query;
10추가: body?: unknown;
11추가: form?: FormData;
12추가: /** json: JSON 으로 해석, text: 문자열 그대로 */
13추가: as?: "json" | "text";
14추가: timeoutMs?: number;
15추가: };
16추가:
17추가: // API 가 돌려준 오류 ({ error: { code, message, details } })
18추가: export class GitGitApiError extends Error {
19추가: readonly status: number;
20추가: readonly code: string;
21추가: readonly details: unknown;
22추가:
23추가: constructor(status: number, code: string, message: string, details?: unknown) {
24추가: super(message);
25추가: this.name = "GitGitApiError";
26추가: this.status = status;
27추가: this.code = code;
28추가: this.details = details;
29추가: }
30추가: }
31추가:
32추가: const segment = (value: string | number) => encodeURIComponent(String(value));
33추가:
34추가: /** /repositories/{owner}/{repo}{suffix} 경로. suffix 는 이미 인코딩된 값이어야 함 */
35추가: export function repositoryPath(owner: string, repo: string, suffix = "") {
36추가: return `/repositories/${segment(owner)}/${segment(repo)}${suffix}`;
37추가: }
38추가:
39추가: export { segment };
40추가:
41추가: export class GitGitClient {
42추가: readonly config: Config;
43추가:
44추가: constructor(config: Config) {
45추가: this.config = config;
46추가: }
47추가:
48추가: get authenticated() {
49추가: return this.config.token !== undefined;
50추가: }
51추가:
52추가: url(path: string, query?: Query) {
53추가: if (!path.startsWith("/") || path.startsWith("//")) throw new Error(`API 경로는 / 로 시작해야 합니다: ${path}`);
54추가: const url = new URL(this.config.apiBase + path);
55추가: // 경로 조작으로 /api/v1 밖이나 다른 호스트로 나가지 않게 막음
56추가: const base = new URL(this.config.apiBase);
57추가: if (url.origin !== base.origin || !(url.pathname + "/").startsWith(base.pathname + "/")) {
58추가: throw new Error(`API 경로가 ${this.config.apiBase} 밖을 가리킵니다: ${path}`);
59추가: }
60추가: for (const [key, value] of Object.entries(query ?? {})) {
61추가: if (value === undefined || value === null || value === "") continue;
62추가: url.searchParams.set(key, String(value));
63추가: }
64추가: return url;
65추가: }
66추가:
67추가: async request<T = unknown>(method: Method, path: string, options: RequestOptions = {}): Promise<T> {
68추가: const headers: Record<string, string> = {
69추가: "User-Agent": `gitgit-mcp/${version}`,
70추가: Accept: options.as === "text" ? "text/plain, application/octet-stream, */*" : "application/json",
71추가: };
72추가: if (this.config.token) headers.Authorization = `Bearer ${this.config.token}`;
73추가:
74추가: let body: BodyInit | undefined;
75추가: if (options.form) {
76추가: body = options.form;
77추가: } else if (options.body !== undefined) {
78추가: headers["Content-Type"] = "application/json";
79추가: body = JSON.stringify(options.body);
80추가: }
81추가:
82추가: const timeoutMs = options.timeoutMs ?? this.config.timeoutMs;
83추가: let response: Response;
84추가: try {
85추가: response = await fetch(this.url(path, options.query), {
86추가: method, headers, body, redirect: "follow", signal: AbortSignal.timeout(timeoutMs),
87추가: });
88추가: } catch (error) {
89추가: const reason = error instanceof Error ? (error.name === "TimeoutError" ? `${timeoutMs}ms 안에 응답이 없습니다` : error.message) : String(error);
90추가: const cause = error instanceof Error && error.cause instanceof Error ? ` (${error.cause.message})` : "";
91추가: throw new Error(`GitGit API(${this.config.apiBase})에 연결하지 못했습니다: ${reason}${cause}`);
92추가: }
93추가:
94추가: if (!response.ok) throw await this.toError(response);
95추가: if (response.status === 204) return undefined as T;
96추가: const text = await response.text();
97추가: if (options.as === "text") return text as T;
98추가: if (text === "") return undefined as T;
99추가: try {
100추가: return JSON.parse(text) as T;
101추가: } catch {
102추가: return text as T;
103추가: }
104추가: }
105추가:
106추가: get<T = unknown>(path: string, query?: Query) {
107추가: return this.request<T>("GET", path, { query });
108추가: }
109추가:
110추가: private async toError(response: Response) {
111추가: const text = await response.text().catch(() => "");
112추가: let code = `HTTP_${response.status}`;
113추가: let message = text.slice(0, 500) || response.statusText;
114추가: let details: unknown;
115추가: try {
116추가: const parsed = JSON.parse(text) as { error?: { code?: string; message?: string; details?: unknown } };
117추가: if (parsed.error) {
118추가: code = parsed.error.code ?? code;
119추가: message = parsed.error.message ?? message;
120추가: details = parsed.error.details;
121추가: }
122추가: } catch {
123추가: // JSON 이 아닌 오류 본문은 그대로 보여 줌
124추가: }
125추가: const retry = response.headers.get("retry-after");
126추가: if (retry) message += ` (Retry-After: ${retry}초)`;
127추가: return new GitGitApiError(response.status, code, message, details);
128추가: }
129추가: }
추가src/config.ts+71-0
@@ -0,0 +1,71 @@
1추가: import { readFileSync } from "node:fs";
2추가:
3추가: export const version = "0.1.0";
4추가:
5추가: export type Config = {
6추가: /** API 서버 주소. 끝에 /api/v1 을 붙인 형태 (예: https://api.gitgit.kr/api/v1) */
7추가: apiBase: string;
8추가: token: string | undefined;
9추가: readOnly: boolean;
10추가: timeoutMs: number;
11추가: uploadTimeoutMs: number;
12추가: maxOutputChars: number;
13추가: /** 시작은 했지만 사용자가 알아야 할 설정 문제 */
14추가: warnings: string[];
15추가: };
16추가:
17추가: const tokenPattern = /^gg[pb]_[A-Za-z0-9_-]{43}$/;
18추가:
19추가: function flag(value: string | undefined) {
20추가: return value !== undefined && ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
21추가: }
22추가:
23추가: function positive(name: string, value: string | undefined, fallback: number) {
24추가: if (value === undefined || value.trim() === "") return fallback;
25추가: const parsed = Number(value);
26추가: if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`${name} 은(는) 양의 정수여야 합니다: ${value}`);
27추가: return parsed;
28추가: }
29추가:
30추가: // GITGIT_API_URL 에는 https://api.gitgit.kr, http://localhost:8080 처럼 서버 주소만 적어도 되고 /api/v1 까지 적어도 됨
31추가: export function apiBaseFrom(value: string) {
32추가: let url: URL;
33추가: try {
34추가: url = new URL(value.trim());
35추가: } catch {
36추가: throw new Error(`GITGIT_API_URL 이 올바른 주소가 아닙니다: ${value}`);
37추가: }
38추가: if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("GITGIT_API_URL 은 http:// 또는 https:// 로 시작해야 합니다.");
39추가: if (url.search || url.hash) throw new Error("GITGIT_API_URL 에 ? 나 # 를 넣지 마세요.");
40추가: const path = url.pathname.replace(/\/+$/, "");
41추가: url.pathname = path.endsWith("/api/v1") ? path : path + "/api/v1";
42추가: return url.toString().replace(/\/+$/, "");
43추가: }
44추가:
45추가: export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
46추가: const warnings: string[] = [];
47추가: let token = env.GITGIT_TOKEN?.trim() || undefined;
48추가: const tokenFile = env.GITGIT_TOKEN_FILE?.trim();
49추가: if (!token && tokenFile) {
50추가: try {
51추가: token = readFileSync(tokenFile, "utf8").trim() || undefined;
52추가: if (!token) warnings.push(`GITGIT_TOKEN_FILE(${tokenFile})이 비어 있어 익명으로 실행합니다.`);
53추가: } catch (error) {
54추가: // 토큰 파일을 아직 만들지 않았어도 공개 저장소 읽기는 되도록 익명으로 시작함
55추가: if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
56추가: warnings.push(`GITGIT_TOKEN_FILE(${tokenFile})이 없어 익명으로 실행합니다. 토큰을 이 파일에 저장한 뒤 MCP 서버를 다시 시작하세요.`);
57추가: }
58추가: }
59추가: if (token && !tokenPattern.test(token)) {
60추가: throw new Error("GITGIT_TOKEN 형식이 올바르지 않습니다. 계정 설정이나 Bot 설정에서 발급한 ggp_ 또는 ggb_ 토큰을 넣으세요.");
61추가: }
62추가: return {
63추가: apiBase: apiBaseFrom(env.GITGIT_API_URL?.trim() || "https://api.gitgit.kr"),
64추가: token,
65추가: readOnly: flag(env.GITGIT_READ_ONLY),
66추가: timeoutMs: positive("GITGIT_TIMEOUT_MS", env.GITGIT_TIMEOUT_MS, 30_000),
67추가: uploadTimeoutMs: positive("GITGIT_UPLOAD_TIMEOUT_MS", env.GITGIT_UPLOAD_TIMEOUT_MS, 10 * 60_000),
68추가: maxOutputChars: positive("GITGIT_MAX_OUTPUT_CHARS", env.GITGIT_MAX_OUTPUT_CHARS, 100_000),
69추가: warnings,
70추가: };
71추가: }
추가src/index.ts+46-0
@@ -0,0 +1,46 @@
1추가: #!/usr/bin/env node
2추가: // GitGit MCP 서버 (stdio). Codex, Claude 데스크탑 앱, Claude Code 가 하위 프로세스로 실행함
3추가: // stdout 은 MCP 메시지 전용이므로 로그는 모두 stderr 로 씀
4추가: import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5추가: import { loadConfig, version } from "./config.ts";
6추가: import { createServer } from "./server.ts";
7추가:
8추가: const args = process.argv.slice(2);
9추가: if (args.includes("--version") || args.includes("-v")) {
10추가: process.stdout.write(`gitgit-mcp ${version}\n`);
11추가: process.exit(0);
12추가: }
13추가: if (args.includes("--help") || args.includes("-h")) {
14추가: process.stdout.write(`gitgit-mcp ${version} — GitGit REST API 용 MCP 서버 (stdio)
15추가:
16추가: 환경 변수
17추가: GITGIT_API_URL API 서버 주소 (기본 https://api.gitgit.kr, 개발: http://localhost:8080)
18추가: GITGIT_TOKEN ggp_ 또는 ggb_ 로 시작하는 액세스 토큰 (없으면 공개 저장소 읽기만)
19추가: GITGIT_TOKEN_FILE 토큰을 담은 파일 경로 (GITGIT_TOKEN 대신)
20추가: GITGIT_READ_ONLY 1 이면 읽기 도구만 등록
21추가: GITGIT_TIMEOUT_MS API 요청 제한 시간 (기본 30000)
22추가: GITGIT_UPLOAD_TIMEOUT_MS Asset 업로드 제한 시간 (기본 600000)
23추가: GITGIT_MAX_OUTPUT_CHARS 도구 응답 최대 글자 수 (기본 100000)
24추가: `);
25추가: process.exit(0);
26추가: }
27추가:
28추가: let config;
29추가: try {
30추가: config = loadConfig();
31추가: } catch (error) {
32추가: process.stderr.write(`[gitgit-mcp] 설정 오류: ${error instanceof Error ? error.message : String(error)}\n`);
33추가: process.exit(1);
34추가: }
35추가:
36추가: const { server, skipped } = createServer(config);
37추가: await server.connect(new StdioServerTransport());
38추가: process.stderr.write(`[gitgit-mcp] ${version} 시작: ${config.apiBase} (${config.token ? "토큰 인증" : "익명"}` +
39추가: `${config.readOnly ? `, 읽기 전용: 쓰기 도구 ${skipped.length}개 제외` : ""})\n`);
40추가: for (const warning of config.warnings) process.stderr.write(`[gitgit-mcp] 경고: ${warning}\n`);
41추가:
42추가: const shutdown = () => {
43추가: void server.close().finally(() => process.exit(0));
44추가: };
45추가: process.on("SIGINT", shutdown);
46추가: process.on("SIGTERM", shutdown);
추가src/server.ts+33-0
@@ -0,0 +1,33 @@
1추가: import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2추가: import { GitGitClient } from "./client.ts";
3추가: import { type Config, version } from "./config.ts";
4추가: import { createRegistrar } from "./tooling.ts";
5추가: import { registerAccountTools } from "./tools/account.ts";
6추가: import { registerCodeTools } from "./tools/code.ts";
7추가: import { registerGenericTools } from "./tools/generic.ts";
8추가: import { registerIssueTools } from "./tools/issues.ts";
9추가: import { registerPullTools } from "./tools/pulls.ts";
10추가: import { registerReleaseTools } from "./tools/releases.ts";
11추가:
12추가: const instructions = `GitGit(gitgit.kr)은 독립 Git 호스팅 플랫폼입니다. 이 서버의 도구는 GitGit REST API(/api/v1)를 부릅니다. GitHub 와는 별개의 서비스이므로 GitHub 도구나 gh CLI 로 GitGit 저장소를 다루지 마세요.
13추가: - 저장소는 owner(사용자명 또는 조직 slug)와 repo(이름)로 가리킵니다. 처음에는 get_repository 로 기본 브랜치와 README 를 확인하세요.
14추가: - 목록 응답의 nextCursor 가 null 이 아니면 다음 쪽이 있습니다. Issue/PR/댓글 목록은 before, 나머지는 cursor 에 그 값을 넣습니다.
15추가: - PR 을 병합하기 전에는 get_pull 로 baseOid/headOid 를 받고 Diff 를 확인한 뒤, 그 OID 를 merge_pull 의 expectedBaseOid/expectedHeadOid 로 넘기세요.
16추가: - 코드 변경(커밋, Push)은 API 가 아니라 git CLI 로 합니다. clone 주소는 get_repository 의 sshUrl/httpUrl 입니다.
17추가: - 오류 코드 INSUFFICIENT_SCOPE 는 토큰 범위 부족, TOKEN_NOT_ALLOWED 는 토큰으로 할 수 없는 작업, 비공개 저장소의 권한 없음은 404 입니다.`;
18추가:
19추가: export function createServer(config: Config) {
20추가: const client = new GitGitClient(config);
21추가: const server = new McpServer(
22추가: { name: "gitgit", title: "GitGit", version },
23추가: { instructions: instructions + (config.readOnly ? "\n- 지금은 읽기 전용 모드라 쓰기 도구가 없습니다." : ""), capabilities: { tools: {} } },
24추가: );
25추가: const { register, skipped } = createRegistrar(server, { client });
26추가: registerAccountTools(register);
27추가: registerCodeTools(register);
28추가: registerIssueTools(register);
29추가: registerPullTools(register);
30추가: registerReleaseTools(register);
31추가: registerGenericTools(register, config.readOnly);
32추가: return { server, client, skipped };
33추가: }
추가src/tooling.ts+89-0
@@ -0,0 +1,89 @@
1추가: import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2추가: import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
3추가: import { z } from "zod";
4추가: import { GitGitApiError, type GitGitClient } from "./client.ts";
5추가:
6추가: type Shape = z.ZodRawShape;
7추가: type Kind = "read" | "write" | "destructive";
8추가:
9추가: export type ToolContext = { client: GitGitClient };
10추가: export type ToolDefinition<S extends Shape> = {
11추가: title: string;
12추가: description: string;
13추가: kind: Kind;
14추가: input: S;
15추가: /** 같은 입력으로 다시 불러도 결과가 같은 쓰기 작업 (PATCH, PUT 등) */
16추가: idempotent?: boolean;
17추가: run: (args: z.infer<z.ZodObject<S>>, context: ToolContext) => Promise<unknown>;
18추가: };
19추가:
20추가: export type Registrar = <S extends Shape>(name: string, definition: ToolDefinition<S>) => void;
21추가:
22추가: // 공통 입력 필드
23추가: export const owner = z.string().min(1).max(100).describe("저장소 소유자(사용자명 또는 조직 slug). 예: gitgit");
24추가: export const repo = z.string().min(1).max(100).describe("저장소 이름. 예: website");
25추가: export const limit = z.number().int().min(1).max(100).optional().describe("한 번에 받을 개수 (1~100, 기본 30)");
26추가: export const cursor = z.string().max(8192).optional().describe("이전 응답의 nextCursor 값. 다음 쪽을 받을 때 사용");
27추가: export const before = z.number().int().positive().optional().describe("이전 응답의 nextCursor 값(번호). 다음 쪽을 받을 때 사용");
28추가: export const ref = z.string().min(1).max(1024).optional().describe("브랜치, 태그 또는 커밋 OID. 생략하면 기본 브랜치");
29추가: export const number = z.number().int().positive().describe("저장소 안의 Issue 또는 PR 번호");
30추가: export const oid = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/, "40자 또는 64자의 소문자 16진수 커밋 OID여야 합니다.");
31추가:
32추가: export function text(value: unknown, maxChars: number): CallToolResult {
33추가: let output = typeof value === "string" ? value : JSON.stringify(value ?? { ok: true }, null, 2);
34추가: if (output.length > maxChars) {
35추가: output = output.slice(0, maxChars) +
36추가: `\n\n… (출력이 ${output.length.toLocaleString()}자라서 ${maxChars.toLocaleString()}자에서 잘랐습니다. ` +
37추가: "범위를 좁히거나 limit, path, startLine/endLine 같은 입력으로 나눠 조회하세요.)";
38추가: }
39추가: return { content: [{ type: "text", text: output }] };
40추가: }
41추가:
42추가: function describeError(error: unknown, client: GitGitClient) {
43추가: if (error instanceof GitGitApiError) {
44추가: const hints: string[] = [];
45추가: if (error.status === 401 && !client.authenticated) hints.push("이 작업에는 GITGIT_TOKEN 환경 변수에 액세스 토큰이 필요합니다.");
46추가: if (error.code === "INSUFFICIENT_SCOPE") hints.push("토큰에 이 작업의 범위(scope)가 없거나, 이 저장소가 토큰의 저장소 범위에 포함되지 않았습니다.");
47추가: if (error.code === "TOKEN_NOT_ALLOWED") hints.push("이 API 는 토큰으로 호출할 수 없거나(세션 전용), Bot 토큰에 허용되지 않은 작업입니다.");
48추가: if (error.status === 404) hints.push("비공개 저장소는 권한이 없으면 404 로 응답합니다. 소유자, 이름, 번호와 토큰 범위를 확인하세요.");
49추가: const details = error.details === undefined ? "" : `\n세부 정보: ${JSON.stringify(error.details)}`;
50추가: return `GitGit API 오류 (HTTP ${error.status} ${error.code}): ${error.message}${details}` +
51추가: (hints.length ? `\n${hints.join("\n")}` : "");
52추가: }
53추가: if (error instanceof z.ZodError) return `입력 오류: ${z.prettifyError(error)}`;
54추가: return error instanceof Error ? error.message : String(error);
55추가: }
56추가:
57추가: export function createRegistrar(server: McpServer, context: ToolContext): { register: Registrar; skipped: string[] } {
58추가: const skipped: string[] = [];
59추가: const register: Registrar = (name, definition) => {
60추가: if (context.client.config.readOnly && definition.kind !== "read") {
61추가: skipped.push(name);
62추가: return;
63추가: }
64추가: server.registerTool(name, {
65추가: title: definition.title,
66추가: description: definition.description,
67추가: inputSchema: definition.input,
68추가: annotations: {
69추가: title: definition.title,
70추가: readOnlyHint: definition.kind === "read",
71추가: destructiveHint: definition.kind === "destructive",
72추가: idempotentHint: definition.kind === "read" || definition.idempotent === true,
73추가: openWorldHint: true,
74추가: },
75추가: }, (async (args: z.infer<z.ZodObject<typeof definition.input>>) => {
76추가: try {
77추가: return text(await definition.run(args, context), context.client.config.maxOutputChars);
78추가: } catch (error) {
79추가: return { isError: true, content: [{ type: "text", text: describeError(error, context.client) }] };
80추가: }
81추가: }) as never);
82추가: };
83추가: return { register, skipped };
84추가: }
85추가:
86추가: /** 값이 undefined 인 키를 빼서 PATCH 본문에 의도하지 않은 필드가 들어가지 않게 함 */
87추가: export function defined<T extends Record<string, unknown>>(value: T) {
88추가: return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as Partial<T>;
89추가: }
추가src/tools/account.ts+85-0
@@ -0,0 +1,85 @@
1추가: import { z } from "zod";
2추가: import { GitGitApiError, repositoryPath, segment } from "../client.ts";
3추가: import { cursor, defined, limit, owner, repo, type Registrar } from "../tooling.ts";
4추가:
5추가: const visibility = z.enum(["private", "public"]);
6추가:
7추가: export function registerAccountTools(register: Registrar) {
8추가: register("whoami", {
9추가: title: "현재 계정 확인",
10추가: description: "GITGIT_TOKEN 으로 인증된 계정(사용자 또는 Bot)과 연결된 GitGit 서버 주소를 확인합니다. 토큰이 없으면 익명 상태라고 알려 줍니다. 토큰에 profile:read 범위가 필요합니다.",
11추가: kind: "read",
12추가: input: {},
13추가: run: async (_args, { client }) => {
14추가: const status = await client.get<Record<string, unknown>>("/status").catch((error: unknown) => ({ error: String(error) }));
15추가: if (!client.authenticated) {
16추가: return { apiBase: client.config.apiBase, authenticated: false, readOnly: client.config.readOnly, status,
17추가: ...(client.config.warnings.length ? { warnings: client.config.warnings } : {}) };
18추가: }
19추가: const me = await client.get<{ user: unknown }>("/me");
20추가: return { apiBase: client.config.apiBase, authenticated: true, readOnly: client.config.readOnly, status, user: me.user };
21추가: },
22추가: });
23추가:
24추가: register("search", {
25추가: title: "GitGit 전체 검색",
26추가: description: "저장소, 사용자, 조직을 이름과 설명으로 검색합니다. 읽을 수 있는 대상만 나옵니다. 저장소 안의 파일, Issue, PR 을 찾으려면 search_repository 를 쓰세요.",
27추가: kind: "read",
28추가: input: {
29추가: q: z.string().min(1).max(200).describe("검색어 (대소문자 구분 없는 부분 일치)"),
30추가: type: z.enum(["repositories", "users", "organizations"]).default("repositories").describe("검색 대상"),
31추가: limit: z.number().int().min(1).max(100).optional().describe("한 번에 받을 개수 (1~100, 기본 20)"),
32추가: cursor,
33추가: },
34추가: run: (args, { client }) => client.get("/search", args),
35추가: });
36추가:
37추가: register("list_repositories", {
38추가: title: "저장소 목록",
39추가: description: "저장소 목록을 봅니다. owner 를 주면 그 사용자나 조직의 저장소(공개 + 내가 읽을 수 있는 비공개)를, 생략하면 토큰 계정이 접근할 수 있는 모든 저장소를 최근 생성 순으로 돌려줍니다. owner 없이 쓰려면 토큰이 필요합니다.",
40추가: kind: "read",
41추가: input: { owner: owner.optional(), limit, cursor },
42추가: run: async ({ owner: name, limit: size, cursor: next }, { client }) => {
43추가: const page = { limit: size, cursor: next };
44추가: if (!name) return client.get("/repositories", page);
45추가: try {
46추가: return await client.get(`/users/${segment(name)}`, page);
47추가: } catch (error) {
48추가: // 사용자 프로필이 없으면 조직으로 다시 찾음
49추가: if (!(error instanceof GitGitApiError) || error.status !== 404) throw error;
50추가: return client.get(`/organizations/${segment(name)}/repositories`, page);
51추가: }
52추가: },
53추가: });
54추가:
55추가: register("get_repository", {
56추가: title: "저장소 정보와 README",
57추가: description: "저장소 메타데이터(공개 범위, 기본 브랜치, 내 역할, clone 주소)와 기본 브랜치의 최상위 파일 목록, README, 최신 커밋을 한 번에 돌려줍니다. 저장소 작업을 시작할 때 먼저 부르세요.",
58추가: kind: "read",
59추가: input: { owner, repo },
60추가: run: ({ owner: o, repo: r }, { client }) => client.get(repositoryPath(o, r, "/overview")),
61추가: });
62추가:
63추가: register("list_organizations", {
64추가: title: "내 조직 목록",
65추가: description: "토큰 계정이 속한 조직과 그 안의 역할을 봅니다. 사용자 토큰과 profile:read 범위가 필요합니다.",
66추가: kind: "read",
67추가: input: { limit, cursor },
68추가: run: (args, { client }) => client.get("/organizations", args),
69추가: });
70추가:
71추가: register("create_repository", {
72추가: title: "저장소 만들기",
73추가: description: "새 빈 Bare 저장소를 만듭니다. owner 를 생략하면 토큰 계정 소유로, 조직 slug 를 주면 그 조직 소유로 만듭니다. 사용자 토큰과 repositories:write 범위가 필요합니다. 응답의 sshUrl 또는 httpUrl 로 첫 Push 를 하면 됩니다.",
74추가: kind: "write",
75추가: input: {
76추가: name: z.string().min(1).max(100).describe("저장소 이름 (영문, 숫자, -, _, .)"),
77추가: owner: owner.optional().describe("조직 소유로 만들 때 조직 slug. 생략하면 내 계정"),
78추가: description: z.string().max(500).optional(),
79추가: visibility: visibility.optional().describe("기본값은 서버 정책(보통 private)"),
80추가: defaultBranch: z.string().min(1).max(100).optional().describe("기본 브랜치 이름 (기본 main)"),
81추가: issuesEnabled: z.boolean().optional(),
82추가: },
83추가: run: (args, { client }) => client.request("POST", "/repositories", { body: defined(args) }),
84추가: });
85추가: }
추가src/tools/code.ts+150-0
@@ -0,0 +1,150 @@
1추가: import { z } from "zod";
2추가: import { repositoryPath, segment } from "../client.ts";
3추가: import { cursor, limit, oid, owner, ref, repo, type Registrar } from "../tooling.ts";
4추가:
5추가: type FileView = { file: { path: string; oid: string; size: number; status: "text" | "binary" | "too_large"; content: string | null; rawUrl: string } };
6추가: type DiffFile = { path: string; change: string; status: string; patch: string | null };
7추가:
8추가: const path = z.string().min(1).max(4096).describe("저장소 루트 기준 파일 경로. 예: src/index.ts");
9추가: // too_large 파일을 Raw 로 다시 받을 때의 상한. 이보다 크면 메타데이터만 돌려줌
10추가: const rawFallbackBytes = 5 * 1024 * 1024;
11추가:
12추가: function sliceLines(content: string, startLine?: number, endLine?: number, numbered = false) {
13추가: const lines = content.split("\n");
14추가: if (lines.at(-1) === "") lines.pop();
15추가: const start = Math.max(1, startLine ?? 1);
16추가: const end = Math.min(lines.length, endLine ?? lines.length);
17추가: const picked = lines.slice(start - 1, end);
18추가: const width = String(end).length;
19추가: const body = numbered ? picked.map((line, index) => `${String(start + index).padStart(width)}\t${line}`).join("\n") : picked.join("\n");
20추가: return { totalLines: lines.length, start, end: Math.max(start - 1, end), body };
21추가: }
22추가:
23추가: export function filterDiff<T extends { files: DiffFile[] }>(diff: T | null, paths?: string[], includePatch = true) {
24추가: if (!diff) return diff;
25추가: const wanted = paths?.length ? new Set(paths) : undefined;
26추가: const prefixes = paths?.filter((item) => item.endsWith("/")) ?? [];
27추가: const files = diff.files
28추가: .filter((file) => !wanted || wanted.has(file.path) || prefixes.some((prefix) => file.path.startsWith(prefix)))
29추가: .map((file) => (includePatch ? file : { ...file, patch: undefined }));
30추가: return { ...diff, files };
31추가: }
32추가:
33추가: export const diffPaths = z.array(z.string().min(1).max(4096)).max(200).optional()
34추가: .describe("이 경로의 파일만 돌려줍니다. / 로 끝나면 그 폴더 아래 전체");
35추가:
36추가: export function registerCodeTools(register: Registrar) {
37추가: register("list_tree", {
38추가: title: "폴더 내용 보기",
39추가: description: "특정 브랜치/태그/커밋 시점의 폴더 안 파일과 하위 폴더 목록을 봅니다. 그 폴더에 README 가 있으면 내용도 함께 옵니다.",
40추가: kind: "read",
41추가: input: { owner, repo, path: z.string().max(4096).optional().describe("폴더 경로. 생략하면 저장소 루트"), ref },
42추가: run: ({ owner: o, repo: r, path: p, ref: at }, { client }) => client.get(repositoryPath(o, r, "/code"), { path: p, ref: at }),
43추가: });
44추가:
45추가: register("read_file", {
46추가: title: "파일 읽기",
47추가: description: "파일 내용을 읽습니다. startLine/endLine 으로 일부 줄만 읽을 수 있고, lineNumbers 를 켜면 줄 번호를 붙입니다. 바이너리 파일은 크기와 Raw 주소만 돌려줍니다.",
48추가: kind: "read",
49추가: input: {
50추가: owner, repo, path, ref,
51추가: startLine: z.number().int().positive().optional().describe("읽기 시작할 줄 (1부터)"),
52추가: endLine: z.number().int().positive().optional().describe("마지막으로 읽을 줄 (포함)"),
53추가: lineNumbers: z.boolean().default(false).describe("각 줄 앞에 줄 번호를 붙일지"),
54추가: },
55추가: run: async ({ owner: o, repo: r, path: p, ref: at, startLine, endLine, lineNumbers }, { client }) => {
56추가: const { file } = await client.get<FileView>(repositoryPath(o, r, "/file"), { path: p, ref: at });
57추가: const meta = { path: file.path, oid: file.oid, size: file.size, rawUrl: file.rawUrl };
58추가: let content = file.content;
59추가: if (file.status === "binary") return { ...meta, status: "binary", note: "바이너리 파일이라 내용을 표시하지 않습니다." };
60추가: if (file.status === "too_large") {
61추가: if (file.size > rawFallbackBytes) {
62추가: return { ...meta, status: "too_large", note: `파일이 ${rawFallbackBytes} 바이트보다 커서 내용을 가져오지 않았습니다.` };
63추가: }
64추가: // 미리보기 한도(줄 수, 크기)를 넘은 텍스트는 Raw 로 받아 필요한 줄만 잘라 줌
65추가: const raw = new URL(file.rawUrl, client.config.apiBase);
66추가: content = await client.request<string>("GET", repositoryPath(o, r, "/raw"), {
67추가: as: "text", query: { ref: raw.searchParams.get("ref") ?? at, path: p },
68추가: });
69추가: }
70추가: const sliced = sliceLines(content ?? "", startLine, endLine, lineNumbers);
71추가: const header = `# ${o}/${r}:${file.path} (blob ${file.oid}, ${file.size} bytes, ` +
72추가: `lines ${sliced.start}-${sliced.end} of ${sliced.totalLines})`;
73추가: return `${header}\n${sliced.body}`;
74추가: },
75추가: });
76추가:
77추가: register("list_branches", {
78추가: title: "브랜치 목록",
79추가: description: "브랜치 이름과 각 브랜치의 최신 커밋 OID, 기본 브랜치를 봅니다.",
80추가: kind: "read",
81추가: input: { owner, repo, limit, cursor },
82추가: run: ({ owner: o, repo: r, ...page }, { client }) => client.get(repositoryPath(o, r, "/branches"), page),
83추가: });
84추가:
85추가: register("list_tags", {
86추가: title: "태그 목록",
87추가: description: "태그 이름과 가리키는 OID 를 봅니다.",
88추가: kind: "read",
89추가: input: { owner, repo, limit, cursor },
90추가: run: ({ owner: o, repo: r, ...page }, { client }) => client.get(repositoryPath(o, r, "/tags"), page),
91추가: });
92추가:
93추가: register("list_commits", {
94추가: title: "커밋 이력",
95추가: description: "브랜치/태그/커밋에서 거슬러 올라가는 커밋 목록(OID, 메시지)을 최신순으로 봅니다.",
96추가: kind: "read",
97추가: input: { owner, repo, ref, limit, cursor },
98추가: run: ({ owner: o, repo: r, ...query }, { client }) => client.get(repositoryPath(o, r, "/commits"), query),
99추가: });
100추가:
101추가: register("get_commit", {
102추가: title: "커밋 상세와 Diff",
103추가: description: "커밋의 작성자, 부모 커밋, 메시지와 변경 파일별 Diff 를 봅니다. paths 로 특정 파일만, includePatch=false 로 변경 파일 목록만 받을 수 있습니다.",
104추가: kind: "read",
105추가: input: {
106추가: owner, repo, oid: oid.describe("커밋 OID (전체 40자 또는 64자)"),
107추가: paths: diffPaths,
108추가: includePatch: z.boolean().default(true).describe("false 면 Diff 본문 없이 변경 파일 목록만"),
109추가: },
110추가: run: async ({ owner: o, repo: r, oid: id, paths, includePatch }, { client }) => {
111추가: const detail = await client.get<{ commit: unknown; diff: { files: DiffFile[] } | null }>(repositoryPath(o, r, `/commits/${segment(id)}`));
112추가: return { ...detail, diff: filterDiff(detail.diff, paths, includePatch) };
113추가: },
114추가: });
115추가:
116추가: register("search_repository", {
117추가: title: "저장소 안 검색",
118추가: description: "저장소 안에서 파일 이름(files), Issue 제목(issues), PR 제목(pulls)을 검색합니다. 파일 본문 전체 검색은 지원하지 않습니다.",
119추가: kind: "read",
120추가: input: {
121추가: owner, repo,
122추가: q: z.string().min(1).max(200).describe("검색어"),
123추가: type: z.enum(["files", "issues", "pulls"]).default("files"),
124추가: ref: ref.describe("files 검색에서만 사용. 생략하면 기본 브랜치"),
125추가: state: z.enum(["open", "closed", "merged", "all"]).optional().describe("issues, pulls 검색에서만 사용 (merged 는 pulls 만)"),
126추가: limit: z.number().int().min(1).max(100).optional().describe("한 번에 받을 개수 (1~100, 기본 20)"),
127추가: cursor,
128추가: },
129추가: run: ({ owner: o, repo: r, type, ref: at, state, ...rest }, { client }) => client.get(repositoryPath(o, r, "/search"), {
130추가: ...rest, type, ...(type === "files" ? { ref: at } : { state }),
131추가: }),
132추가: });
133추가:
134추가: register("compare_branches", {
135추가: title: "브랜치 비교",
136추가: description: "PR 을 열기 전에 기준 브랜치와 작업 브랜치의 차이(merge base, 커밋, 변경 파일)를 확인합니다.",
137추가: kind: "read",
138추가: input: {
139추가: owner, repo,
140추가: baseBranch: z.string().min(1).max(1024).describe("병합 대상(기준) 브랜치"),
141추가: headBranch: z.string().min(1).max(1024).describe("변경이 있는 작업 브랜치"),
142추가: paths: diffPaths,
143추가: includePatch: z.boolean().default(true),
144추가: },
145추가: run: async ({ owner: o, repo: r, baseBranch, headBranch, paths, includePatch }, { client }) => {
146추가: const result = await client.get<{ diff?: { files: DiffFile[] } | null }>(repositoryPath(o, r, "/compare"), { baseBranch, headBranch });
147추가: return result && typeof result === "object" && "diff" in result ? { ...result, diff: filterDiff(result.diff ?? null, paths, includePatch) } : result;
148추가: },
149추가: });
150추가: }
추가src/tools/generic.ts+29-0
@@ -0,0 +1,29 @@
1추가: import { z } from "zod";
2추가: import type { Registrar } from "../tooling.ts";
3추가:
4추가: const queryValue = z.union([z.string(), z.number(), z.boolean()]);
5추가:
6추가: export function registerGenericTools(register: Registrar, readOnly: boolean) {
7추가: register("api_request", {
8추가: title: "GitGit REST API 직접 호출",
9추가: description: "전용 도구가 없는 GitGit REST API(/api/v1 아래)를 직접 부릅니다. 예: GET /repositories/{owner}/{name}/branch-protections, POST /repositories/{owner}/{name}/labels. " +
10추가: "경로 목록과 입력 형식은 GET /openapi.json 에서 확인할 수 있습니다. 토큰으로 허용되지 않는 세션 전용 API 는 TOKEN_NOT_ALLOWED 로 거부됩니다." +
11추가: (readOnly ? " 읽기 전용 모드라 GET 만 허용됩니다." : " 쓰기 요청은 실제 데이터를 바꾸므로 사용자가 요청한 작업인지 확인하고 쓰세요."),
12추가: kind: readOnly ? "read" : "destructive",
13추가: input: {
14추가: method: (readOnly ? z.enum(["GET"]) : z.enum(["GET", "POST", "PATCH", "PUT", "DELETE"])).default("GET"),
15추가: path: z.string().min(1).max(4096).regex(/^\/(?!\/)/, "/ 로 시작하는 /api/v1 기준 경로여야 합니다.")
16추가: .describe("/api/v1 뒤의 경로. 경로 안의 값은 URL 인코딩하세요. 예: /repositories/gitgit/website/branch-protections"),
17추가: query: z.record(z.string(), queryValue).optional().describe("쿼리 문자열 값"),
18추가: body: z.unknown().optional().describe("JSON 본문 (POST, PATCH, PUT, DELETE)"),
19추가: },
20추가: run: ({ method, path, query, body }, { client }) => {
21추가: if (path.split(/[/?#]/).some((part) => part === ".." || part === "." || /%2e%2e/i.test(part))) {
22추가: throw new Error("경로에 . 또는 .. 를 쓸 수 없습니다.");
23추가: }
24추가: if (path.includes("?") || path.includes("#")) throw new Error("쿼리는 path 대신 query 입력에 넣으세요.");
25추가: if (method === "GET" && body !== undefined) throw new Error("GET 요청에는 body 를 줄 수 없습니다.");
26추가: return client.request(method, path, { query, body });
27추가: },
28추가: });
29추가: }
추가src/tools/issues.ts+86-0
@@ -0,0 +1,86 @@
1추가: import { z } from "zod";
2추가: import { repositoryPath } from "../client.ts";
3추가: import { before, cursor, defined, limit, number, owner, repo, type Registrar } from "../tooling.ts";
4추가:
5추가: const title = z.string().min(1).max(200);
6추가: const body = z.string().max(8000);
7추가: const comment = z.string().min(1).max(8000).describe("Markdown 본문");
8추가: const issuePath = (o: string, r: string, n: number, suffix = "") => repositoryPath(o, r, `/issues/${n}${suffix}`);
9추가:
10추가: export function registerIssueTools(register: Registrar) {
11추가: register("list_issues", {
12추가: title: "Issue 목록",
13추가: description: "저장소의 Issue 를 번호 역순으로 봅니다. 다음 쪽은 응답의 nextCursor 를 before 에 넣어 받습니다.",
14추가: kind: "read",
15추가: input: { owner, repo, state: z.enum(["open", "closed", "all"]).default("open"), limit, before },
16추가: run: ({ owner: o, repo: r, ...query }, { client }) => client.get(repositoryPath(o, r, "/issues"), query),
17추가: });
18추가:
19추가: register("get_issue", {
20추가: title: "Issue 상세",
21추가: description: "Issue 의 제목, 본문, 상태, 담당자, Label 과 (기본으로) 첫 쪽 댓글을 함께 봅니다.",
22추가: kind: "read",
23추가: input: {
24추가: owner, repo, number,
25추가: includeComments: z.boolean().default(true).describe("댓글 첫 쪽을 함께 받을지"),
26추가: commentLimit: limit.describe("함께 받을 댓글 수 (1~100, 기본 30)"),
27추가: },
28추가: run: async ({ owner: o, repo: r, number: n, includeComments, commentLimit }, { client }) => {
29추가: const detail = await client.get<Record<string, unknown>>(issuePath(o, r, n));
30추가: if (!includeComments) return detail;
31추가: const comments = await client.get(issuePath(o, r, n, "/comments"), { limit: commentLimit });
32추가: return { ...detail, comments };
33추가: },
34추가: });
35추가:
36추가: register("list_issue_comments", {
37추가: title: "Issue 댓글 목록",
38추가: description: "Issue 댓글을 쪽 단위로 봅니다. 다음 쪽은 nextCursor 를 before 에 넣습니다.",
39추가: kind: "read",
40추가: input: { owner, repo, number, limit, before: z.string().max(8192).optional().describe("이전 응답의 nextCursor") },
41추가: run: ({ owner: o, repo: r, number: n, ...page }, { client }) => client.get(issuePath(o, r, n, "/comments"), page),
42추가: });
43추가:
44추가: register("list_labels", {
45추가: title: "Label 목록",
46추가: description: "저장소에 정의된 Label(id, 이름, 색)을 봅니다. update_issue 의 labelIds 에 이 id 를 씁니다.",
47추가: kind: "read",
48추가: input: { owner, repo, limit, cursor },
49추가: run: ({ owner: o, repo: r, ...page }, { client }) => client.get(repositoryPath(o, r, "/labels"), page),
50추가: });
51추가:
52추가: register("create_issue", {
53추가: title: "Issue 만들기",
54추가: description: "새 Issue 를 엽니다. issues:write 범위가 필요합니다.",
55추가: kind: "write",
56추가: input: { owner, repo, title, body: body.optional().describe("Markdown 본문") },
57추가: run: ({ owner: o, repo: r, ...fields }, { client }) =>
58추가: client.request("POST", repositoryPath(o, r, "/issues"), { body: defined(fields) }),
59추가: });
60추가:
61추가: register("update_issue", {
62추가: title: "Issue 수정, 닫기, 다시 열기",
63추가: description: "Issue 의 제목, 본문, 상태(open/closed), 담당자, Label 을 바꿉니다. 준 필드만 바뀝니다. labelIds 는 전체 목록으로 교체됩니다. 담당자를 빼려면 assignee 에 null 을 주세요.",
64추가: kind: "write",
65추가: idempotent: true,
66추가: input: {
67추가: owner, repo, number,
68추가: title: title.optional(),
69추가: body: body.optional(),
70추가: state: z.enum(["open", "closed"]).optional(),
71추가: assignee: z.string().min(1).max(100).nullable().optional().describe("담당자 사용자명. null 이면 해제"),
72추가: labelIds: z.array(z.uuid()).max(100).optional().describe("붙일 Label id 전체 목록 (list_labels 참고)"),
73추가: },
74추가: run: ({ owner: o, repo: r, number: n, ...fields }, { client }) =>
75추가: client.request("PATCH", issuePath(o, r, n), { body: defined(fields) }),
76추가: });
77추가:
78추가: register("create_issue_comment", {
79추가: title: "Issue 댓글 달기",
80추가: description: "Issue 에 댓글을 남깁니다. issues:write 범위가 필요합니다.",
81추가: kind: "write",
82추가: input: { owner, repo, number, body: comment },
83추가: run: ({ owner: o, repo: r, number: n, body: text }, { client }) =>
84추가: client.request("POST", issuePath(o, r, n, "/comments"), { body: { body: text } }),
85추가: });
86추가: }
추가src/tools/pulls.ts+172-0
@@ -0,0 +1,172 @@
1추가: import { z } from "zod";
2추가: import type { GitGitClient } from "../client.ts";
3추가: import { repositoryPath } from "../client.ts";
4추가: import { before, cursor, defined, limit, number, oid, owner, repo, type Registrar } from "../tooling.ts";
5추가: import { diffPaths, filterDiff } from "./code.ts";
6추가:
7추가: type DiffFile = { path: string; change: string; status: string; patch: string | null };
8추가: type PullDiff = { baseOid: string | null; headOid: string | null; mergeBaseOid: string | null; diff: { status: string; files: DiffFile[] } | null };
9추가:
10추가: const title = z.string().min(1).max(200);
11추가: const body = z.string().max(8000);
12추가: const comment = z.string().min(1).max(8000).describe("Markdown 본문");
13추가: const branch = z.string().min(1).max(1024);
14추가: const issueNumbers = z.array(z.number().int().positive()).max(20).describe("이 PR 과 연결할 Issue 번호");
15추가: const side = z.enum(["old", "new"]).describe("old: 삭제/변경 전 줄, new: 추가/변경 후 줄");
16추가: const pullPath = (o: string, r: string, n: number, suffix = "") => repositoryPath(o, r, `/pulls/${n}${suffix}`);
17추가: const beforeCursor = z.string().max(8192).optional().describe("이전 응답의 nextCursor");
18추가:
19추가: const diffOf = (client: GitGitClient, o: string, r: string, n: number) => client.get<PullDiff>(pullPath(o, r, n, "/diff"));
20추가:
21추가: export function registerPullTools(register: Registrar) {
22추가: register("list_pulls", {
23추가: title: "PR 목록",
24추가: description: "저장소의 Pull Request 를 번호 역순으로 봅니다. 다음 쪽은 nextCursor 를 before 에 넣습니다.",
25추가: kind: "read",
26추가: input: { owner, repo, state: z.enum(["open", "closed", "merged", "all"]).default("open"), limit, before },
27추가: run: ({ owner: o, repo: r, ...query }, { client }) => client.get(repositoryPath(o, r, "/pulls"), query),
28추가: });
29추가:
30추가: register("get_pull", {
31추가: title: "PR 상세",
32추가: description: "PR 의 제목, 본문, 상태, 브랜치, 연결된 Issue 와 함께 현재 baseOid/headOid/mergeBaseOid 및 변경 파일 목록(Diff 본문 제외)을 봅니다. 리뷰나 병합 전에 부르세요. Diff 본문은 get_pull_diff 로 받습니다.",
33추가: kind: "read",
34추가: input: { owner, repo, number },
35추가: run: async ({ owner: o, repo: r, number: n }, { client }) => {
36추가: const [detail, diff] = await Promise.all([client.get<{ pull: unknown }>(pullPath(o, r, n)), diffOf(client, o, r, n)]);
37추가: return { ...detail, baseOid: diff.baseOid, headOid: diff.headOid, mergeBaseOid: diff.mergeBaseOid,
38추가: diffStatus: diff.diff?.status ?? null, files: filterDiff(diff.diff, undefined, false)?.files ?? [] };
39추가: },
40추가: });
41추가:
42추가: register("get_pull_diff", {
43추가: title: "PR Diff",
44추가: description: "PR 의 변경 파일별 Diff 를 봅니다. 큰 PR 은 paths 로 파일을 나눠 받으세요.",
45추가: kind: "read",
46추가: input: { owner, repo, number, paths: diffPaths },
47추가: run: async ({ owner: o, repo: r, number: n, paths }, { client }) => {
48추가: const diff = await diffOf(client, o, r, n);
49추가: return { ...diff, diff: filterDiff(diff.diff, paths) };
50추가: },
51추가: });
52추가:
53추가: register("list_pull_commits", {
54추가: title: "PR 커밋 목록",
55추가: description: "PR 작업 브랜치에서 기준 브랜치에 없는 커밋 목록을 봅니다.",
56추가: kind: "read",
57추가: input: { owner, repo, number, limit, cursor },
58추가: run: ({ owner: o, repo: r, number: n, ...page }, { client }) => client.get(pullPath(o, r, n, "/commits"), page),
59추가: });
60추가:
61추가: register("list_pull_comments", {
62추가: title: "PR 댓글 목록",
63추가: description: "PR 의 일반 댓글과 줄 댓글(anchor 포함)을 봅니다. 줄이 바뀐 줄 댓글은 이전 변경분 표시가 붙습니다.",
64추가: kind: "read",
65추가: input: { owner, repo, number, limit, before: beforeCursor },
66추가: run: ({ owner: o, repo: r, number: n, ...page }, { client }) => client.get(pullPath(o, r, n, "/comments"), page),
67추가: });
68추가:
69추가: register("list_pull_reviews", {
70추가: title: "PR 리뷰 목록",
71추가: description: "PR 에 남은 리뷰(승인, 변경 요청, 의견)와 각 리뷰가 본 커밋을 봅니다.",
72추가: kind: "read",
73추가: input: { owner, repo, number, limit, before: beforeCursor },
74추가: run: ({ owner: o, repo: r, number: n, ...page }, { client }) => client.get(pullPath(o, r, n, "/reviews"), page),
75추가: });
76추가:
77추가: register("create_pull", {
78추가: title: "PR 열기",
79추가: description: "같은 저장소의 headBranch 를 baseBranch 로 병합하자는 Pull Request 를 엽니다. pulls:write 범위가 필요합니다. 먼저 compare_branches 로 차이를 확인하면 좋습니다.",
80추가: kind: "write",
81추가: input: {
82추가: owner, repo, title,
83추가: body: body.optional().describe("Markdown 본문"),
84추가: baseBranch: branch.describe("병합 대상 브랜치 (예: main)"),
85추가: headBranch: branch.describe("변경이 있는 작업 브랜치"),
86추가: linkedIssueNumbers: issueNumbers.optional(),
87추가: },
88추가: run: ({ owner: o, repo: r, ...fields }, { client }) =>
89추가: client.request("POST", repositoryPath(o, r, "/pulls"), { body: defined(fields) }),
90추가: });
91추가:
92추가: register("update_pull", {
93추가: title: "PR 수정, 닫기, 다시 열기",
94추가: description: "PR 의 제목, 본문, 상태(open/closed), 연결 Issue 를 바꿉니다. 준 필드만 바뀝니다. 병합은 merge_pull 을 쓰세요.",
95추가: kind: "write",
96추가: idempotent: true,
97추가: input: {
98추가: owner, repo, number,
99추가: title: title.optional(), body: body.optional(),
100추가: state: z.enum(["open", "closed"]).optional(),
101추가: linkedIssueNumbers: issueNumbers.optional(),
102추가: },
103추가: run: ({ owner: o, repo: r, number: n, ...fields }, { client }) =>
104추가: client.request("PATCH", pullPath(o, r, n), { body: defined(fields) }),
105추가: });
106추가:
107추가: register("create_pull_comment", {
108추가: title: "PR 댓글 달기",
109추가: description: "PR 에 일반 댓글을 남기거나, path/line/side 를 주면 특정 줄에 줄 댓글을 남깁니다. commitOid 를 생략하면 현재 headOid 를 씁니다. replyToId 로 기존 댓글에 답글을 달 수 있습니다.",
110추가: kind: "write",
111추가: input: {
112추가: owner, repo, number, body: comment,
113추가: path: z.string().min(1).max(1024).optional().describe("줄 댓글을 달 파일 경로"),
114추가: line: z.number().int().positive().optional().describe("줄 번호 (side 기준)"),
115추가: side: side.optional().describe("기본 new"),
116추가: commitOid: oid.optional().describe("줄 댓글이 가리킬 커밋. 생략하면 현재 headOid"),
117추가: replyToId: z.uuid().optional().describe("답글을 달 댓글 id"),
118추가: },
119추가: run: async ({ owner: o, repo: r, number: n, body: text, path, line, side: at, commitOid, replyToId }, { client }) => {
120추가: if ((path === undefined) !== (line === undefined)) throw new Error("줄 댓글에는 path 와 line 을 함께 주세요.");
121추가: let anchor: Record<string, unknown> | undefined;
122추가: if (path !== undefined && line !== undefined) {
123추가: const commit = commitOid ?? (await diffOf(client, o, r, n)).headOid;
124추가: if (!commit) throw new Error("PR 의 headOid 를 확인하지 못했습니다. commitOid 를 직접 주세요.");
125추가: anchor = { commitOid: commit, path, side: at ?? "new", line };
126추가: }
127추가: return client.request("POST", pullPath(o, r, n, "/comments"), { body: defined({ body: text, anchor, replyToId }) });
128추가: },
129추가: });
130추가:
131추가: register("submit_pull_review", {
132추가: title: "PR 리뷰 제출",
133추가: description: "PR 을 승인(approved), 변경 요청(changes_requested) 또는 의견(commented)으로 리뷰합니다. 줄 댓글을 최대 20개까지 함께 남길 수 있습니다. headOid 는 리뷰한 커밋이며, 생략하면 현재 headOid 를 씁니다. 리뷰 뒤 새 커밋이 올라오면 이전 승인은 승인 수에서 빠집니다.",
134추가: kind: "write",
135추가: input: {
136추가: owner, repo, number,
137추가: state: z.enum(["approved", "changes_requested", "commented"]),
138추가: body: body.optional().describe("리뷰 요약 (Markdown)"),
139추가: headOid: oid.optional().describe("리뷰한 커밋 OID. 생략하면 현재 headOid (리뷰 도중 새 커밋이 올라왔다면 직접 주는 편이 안전)"),
140추가: comments: z.array(z.object({
141추가: body: comment, path: z.string().min(1).max(1024), line: z.number().int().positive(), side: side.optional(),
142추가: })).max(20).optional().describe("줄 댓글 목록"),
143추가: },
144추가: run: async ({ owner: o, repo: r, number: n, state, body: text, headOid, comments }, { client }) => {
145추가: const commit = headOid ?? (await diffOf(client, o, r, n)).headOid;
146추가: if (!commit) throw new Error("PR 의 headOid 를 확인하지 못했습니다.");
147추가: return client.request("POST", pullPath(o, r, n, "/reviews"), { body: defined({
148추가: state, headOid: commit, body: text,
149추가: comments: comments?.map((item) => ({
150추가: body: item.body, anchor: { commitOid: commit, path: item.path, side: item.side ?? "new", line: item.line },
151추가: })),
152추가: }) });
153추가: },
154추가: });
155추가:
156추가: register("merge_pull", {
157추가: title: "PR 병합",
158추가: description: "PR 을 Merge Commit(merge) 또는 Squash(squash)로 병합합니다. 확인한 변경분만 병합되도록 get_pull 로 받은 baseOid/headOid 를 expectedBaseOid/expectedHeadOid 에 그대로 넣어야 하며, 그 사이 브랜치가 바뀌면 서버가 거부합니다. 보호 브랜치 규칙(승인 수, 병합 역할)과 pulls:merge 범위가 필요합니다.",
159추가: kind: "destructive",
160추가: input: {
161추가: owner, repo, number,
162추가: method: z.enum(["merge", "squash"]).default("merge"),
163추가: expectedBaseOid: oid.describe("get_pull 의 baseOid"),
164추가: expectedHeadOid: oid.describe("get_pull 의 headOid"),
165추가: deleteHeadBranch: z.boolean().optional().describe("병합 후 보호되지 않은 작업 브랜치 삭제"),
166추가: commitTitle: title.optional(),
167추가: commitBody: body.optional(),
168추가: },
169추가: run: ({ owner: o, repo: r, number: n, ...fields }, { client }) =>
170추가: client.request("POST", pullPath(o, r, n, "/merge"), { body: defined(fields) }),
171추가: });
172추가: }
추가src/tools/releases.ts+117-0
@@ -0,0 +1,117 @@
1추가: import { openAsBlob } from "node:fs";
2추가: import { stat } from "node:fs/promises";
3추가: import { basename, extname, isAbsolute, resolve } from "node:path";
4추가: import { z } from "zod";
5추가: import { repositoryPath, segment } from "../client.ts";
6추가: import { cursor, defined, limit, owner, repo, type Registrar } from "../tooling.ts";
7추가:
8추가: const releaseRef = z.string().min(1).max(250);
9추가: const releaseId = z.uuid().describe("Release id (list_releases 참고)");
10추가: const fields = {
11추가: target: releaseRef.optional().describe("태그가 없을 때 태그를 만들 브랜치 이름 또는 커밋 OID. 생략하면 기본 브랜치"),
12추가: name: z.string().max(200).optional().describe("Release 제목"),
13추가: body: z.string().max(20000).optional().describe("Release 노트 (Markdown)"),
14추가: draft: z.boolean().optional().describe("초안이면 쓰기 권한자에게만 보이고 태그를 만들지 않음"),
15추가: prerelease: z.boolean().optional().describe("사전 출시 표시. 최신 Release 에서 제외됨"),
16추가: };
17추가: const itemPath = (o: string, r: string, id: string, suffix = "") => repositoryPath(o, r, `/releases/${segment(id)}${suffix}`);
18추가:
19추가: // 서버가 업로드 형식으로 파일 종류를 기록하므로 흔한 확장자는 알맞은 MIME 형식을 붙임
20추가: const mimeTypes: Record<string, string> = {
21추가: ".zip": "application/zip", ".gz": "application/gzip", ".tgz": "application/gzip", ".tar": "application/x-tar",
22추가: ".xz": "application/x-xz", ".bz2": "application/x-bzip2", ".7z": "application/x-7z-compressed",
23추가: ".txt": "text/plain", ".md": "text/markdown", ".json": "application/json", ".pdf": "application/pdf",
24추가: ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp",
25추가: ".exe": "application/vnd.microsoft.portable-executable", ".msi": "application/x-msi", ".dmg": "application/x-apple-diskimage",
26추가: ".deb": "application/vnd.debian.binary-package", ".rpm": "application/x-rpm", ".apk": "application/vnd.android.package-archive",
27추가: ".jar": "application/java-archive", ".wasm": "application/wasm", ".sha256": "text/plain", ".sig": "application/pgp-signature",
28추가: ".asc": "application/pgp-signature",
29추가: };
30추가:
31추가: export function registerReleaseTools(register: Registrar) {
32추가: register("list_releases", {
33추가: title: "Release 목록",
34추가: description: "저장소의 Release 를 최근 순으로 봅니다. 초안은 쓰기 권한자에게만 보입니다.",
35추가: kind: "read",
36추가: input: { owner, repo, limit, cursor },
37추가: run: ({ owner: o, repo: r, ...page }, { client }) => client.get(repositoryPath(o, r, "/releases"), page),
38추가: });
39추가:
40추가: register("get_release", {
41추가: title: "Release 상세",
42추가: description: "Release 하나와 Asset 목록을 봅니다. id, tag 중 하나를 주거나, 둘 다 생략하면 최신 Release(초안, 사전 출시 제외)를 돌려줍니다.",
43추가: kind: "read",
44추가: input: { owner, repo, id: releaseId.optional(), tag: releaseRef.optional().describe("태그 이름 (/ 포함 가능)") },
45추가: run: ({ owner: o, repo: r, id, tag }, { client }) => {
46추가: if (id && tag) throw new Error("id 와 tag 중 하나만 주세요.");
47추가: if (id) return client.get(itemPath(o, r, id));
48추가: if (tag) return client.get(repositoryPath(o, r, `/releases/tags/${tag.split("/").map(segment).join("/")}`));
49추가: return client.get(repositoryPath(o, r, "/releases/latest"));
50추가: },
51추가: });
52추가:
53추가: register("create_release", {
54추가: title: "Release 게시",
55추가: description: "Git 태그 하나에 제목, 노트를 묶어 Release 를 게시하거나 초안으로 저장합니다. 태그가 없으면 target 에서 서버가 태그를 만듭니다. releases:write 범위가 필요합니다.",
56추가: kind: "write",
57추가: input: { owner, repo, tagName: releaseRef.describe("태그 이름. 예: v1.2.0"), ...fields },
58추가: run: ({ owner: o, repo: r, ...body }, { client }) =>
59추가: client.request("POST", repositoryPath(o, r, "/releases"), { body: defined(body) }),
60추가: });
61추가:
62추가: register("update_release", {
63추가: title: "Release 수정",
64추가: description: "Release 의 태그, 제목, 노트, 초안/사전 출시 상태를 바꿉니다. 초안에서 draft=false 로 바꾸면 게시됩니다.",
65추가: kind: "write",
66추가: idempotent: true,
67추가: input: { owner, repo, id: releaseId, tagName: releaseRef.optional(), ...fields },
68추가: run: ({ owner: o, repo: r, id, ...body }, { client }) =>
69추가: client.request("PATCH", itemPath(o, r, id), { body: defined(body) }),
70추가: });
71추가:
72추가: register("delete_release", {
73추가: title: "Release 삭제",
74추가: description: "Release 와 그 Asset 을 삭제합니다. Git 태그는 남습니다. 되돌릴 수 없습니다.",
75추가: kind: "destructive",
76추가: idempotent: true,
77추가: input: { owner, repo, id: releaseId },
78추가: run: async ({ owner: o, repo: r, id }, { client }) => {
79추가: await client.request("DELETE", itemPath(o, r, id));
80추가: return { deleted: true, id };
81추가: },
82추가: });
83추가:
84추가: register("upload_release_asset", {
85추가: title: "Release Asset 올리기",
86추가: description: "이 MCP 서버가 실행 중인 컴퓨터의 파일을 Release 의 배포 파일(Asset)로 올립니다. filePath 는 절대 경로를 권장합니다. 같은 이름의 Asset 이 있으면 거부됩니다.",
87추가: kind: "write",
88추가: input: {
89추가: owner, repo, id: releaseId,
90추가: filePath: z.string().min(1).describe("올릴 로컬 파일 경로"),
91추가: filename: z.string().min(1).max(255).optional().describe("GitGit 에 저장할 파일 이름. 생략하면 로컬 파일 이름"),
92추가: contentType: z.string().min(1).max(200).optional().describe("MIME 형식. 생략하면 확장자로 추정"),
93추가: },
94추가: run: async ({ owner: o, repo: r, id, filePath, filename, contentType }, { client }) => {
95추가: const path = isAbsolute(filePath) ? filePath : resolve(filePath);
96추가: const info = await stat(path);
97추가: if (!info.isFile()) throw new Error(`일반 파일이 아닙니다: ${path}`);
98추가: const name = filename ?? basename(path);
99추가: const type = contentType ?? mimeTypes[extname(name).toLowerCase()] ?? "application/octet-stream";
100추가: const form = new FormData();
101추가: form.append("file", await openAsBlob(path, { type }), name);
102추가: return client.request("POST", itemPath(o, r, id, "/assets"), { form, timeoutMs: client.config.uploadTimeoutMs });
103추가: },
104추가: });
105추가:
106추가: register("delete_release_asset", {
107추가: title: "Release Asset 삭제",
108추가: description: "Release 의 배포 파일 하나를 삭제합니다. 되돌릴 수 없습니다.",
109추가: kind: "destructive",
110추가: idempotent: true,
111추가: input: { owner, repo, id: releaseId, assetId: z.uuid().describe("Asset id (get_release 참고)") },
112추가: run: async ({ owner: o, repo: r, id, assetId }, { client }) => {
113추가: await client.request("DELETE", itemPath(o, r, id, `/assets/${segment(assetId)}`));
114추가: return { deleted: true, id, assetId };
115추가: },
116추가: });
117추가: }
추가test/server.test.mjs+252-0
@@ -0,0 +1,252 @@
1추가: // MCP 서버를 실제 stdio 하위 프로세스로 띄우고, GitGit API 자리에 모형 HTTP 서버를 두어
2추가: // 도구가 올바른 경로, 쿼리, 본문, 인증 헤더로 API 를 부르는지 확인함
3추가: import assert from "node:assert/strict";
4추가: import { createServer } from "node:http";
5추가: import { mkdtemp, rm, writeFile } from "node:fs/promises";
6추가: import { tmpdir } from "node:os";
7추가: import { join } from "node:path";
8추가: import { after, before, describe, it } from "node:test";
9추가: import { fileURLToPath } from "node:url";
10추가: import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11추가: import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
12추가:
13추가: const entry = fileURLToPath(new URL("../dist/index.js", import.meta.url));
14추가: const token = "ggp_" + "a".repeat(43);
15추가: const headOid = "b".repeat(40);
16추가: const baseOid = "c".repeat(40);
17추가:
18추가: const requests = [];
19추가: const routes = new Map();
20추가: const route = (method, path, handler) => routes.set(`${method} ${path}`, handler);
21추가: const json = (status, body) => ({ status, body });
22추가:
23추가: route("GET", "/api/v1/status", () => json(200, { status: "ok", readsAllowed: true, writesAllowed: true, message: "ok" }));
24추가: route("GET", "/api/v1/me", () => json(200, { user: { id: "u1", username: "alice", name: "Alice" } }));
25추가: route("GET", "/api/v1/users/team", () => json(404, { error: { code: "NOT_FOUND", message: "없음" } }));
26추가: route("GET", "/api/v1/organizations/team/repositories", () => json(200, { repositories: [{ name: "site" }], nextCursor: null }));
27추가: route("GET", "/api/v1/repositories/alice/app/file", (url) => json(200, { file: {
28추가: path: url.searchParams.get("path"), oid: "d".repeat(40), size: 24, status: "text",
29추가: content: "one\ntwo\nthree\nfour\nfive\n", rawUrl: "/api/v1/repositories/alice/app/raw?ref=main&path=a.txt",
30추가: } }));
31추가: route("GET", "/api/v1/repositories/alice/app/pulls/7", () => json(200, { pull: { number: 7, title: "PR", state: "open" } }));
32추가: route("GET", "/api/v1/repositories/alice/app/pulls/7/diff", () => json(200, {
33추가: baseOid, headOid, mergeBaseOid: baseOid,
34추가: diff: { status: "complete", files: [
35추가: { path: "src/a.ts", change: "modified", status: "text", patch: "@@ -1 +1 @@\n-a\n+b" },
36추가: { path: "docs/b.md", change: "added", status: "text", patch: "@@ +1 @@\n+hi" },
37추가: ] },
38추가: }));
39추가: route("POST", "/api/v1/repositories/alice/app/pulls/7/reviews", () => json(201, { review: { id: "r1" }, comments: [] }));
40추가: route("POST", "/api/v1/repositories/alice/app/pulls/7/comments", () => json(201, { comment: { id: "c1" } }));
41추가: route("POST", "/api/v1/repositories/alice/app/pulls/7/merge", () => json(200, { pull: { state: "merged" }, headBranchDeleted: false }));
42추가: route("PATCH", "/api/v1/repositories/alice/app/issues/3", () => json(200, { issue: { number: 3, state: "closed" } }));
43추가: route("GET", "/api/v1/repositories/alice/app/issues/3", () => json(200, { issue: { number: 3 } }));
44추가: route("GET", "/api/v1/repositories/alice/app/issues/3/comments", () => json(200, { comments: [], nextCursor: null }));
45추가: route("GET", "/api/v1/repositories/alice/app/releases/tags/release/v1", () => json(200, { release: { tagName: "release/v1" } }));
46추가: route("POST", "/api/v1/repositories/alice/app/releases/00000000-0000-4000-8000-000000000001/assets", () => json(201, { asset: { filename: "out.zip" } }));
47추가: route("GET", "/api/v1/repositories/alice/private/overview", () => json(403, { error: { code: "INSUFFICIENT_SCOPE", message: "액세스 토큰 범위가 부족합니다." } }));
48추가:
49추가: let api;
50추가: let apiUrl;
51추가: let dir;
52추가:
53추가: async function connect(env = {}) {
54추가: const transport = new StdioClientTransport({
55추가: command: process.execPath, args: [entry], stderr: "ignore",
56추가: env: { PATH: process.env.PATH ?? "", GITGIT_API_URL: apiUrl, GITGIT_TOKEN: token, ...env },
57추가: });
58추가: const client = new Client({ name: "gitgit-mcp-test", version: "0.0.0" });
59추가: await client.connect(transport);
60추가: return client;
61추가: }
62추가:
63추가: async function call(client, name, args = {}) {
64추가: const result = await client.callTool({ name, arguments: args });
65추가: return { error: Boolean(result.isError), text: result.content[0].text };
66추가: }
67추가:
68추가: const last = () => requests.at(-1);
69추가:
70추가: before(async () => {
71추가: dir = await mkdtemp(join(tmpdir(), "gitgit-mcp-test-"));
72추가: api = createServer(async (request, response) => {
73추가: const chunks = [];
74추가: for await (const chunk of request) chunks.push(chunk);
75추가: const raw = Buffer.concat(chunks);
76추가: const url = new URL(request.url, "http://localhost");
77추가: const type = request.headers["content-type"] ?? "";
78추가: requests.push({
79추가: method: request.method, path: url.pathname, query: Object.fromEntries(url.searchParams), headers: request.headers,
80추가: body: type.startsWith("application/json") ? JSON.parse(raw.toString()) : raw.toString("latin1"),
81추가: });
82추가: const handler = routes.get(`${request.method} ${url.pathname}`);
83추가: const { status, body } = handler ? handler(url) : json(404, { error: { code: "NOT_FOUND", message: "모형에 없는 경로" } });
84추가: response.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
85추가: });
86추가: await new Promise((resolve) => api.listen(0, "127.0.0.1", resolve));
87추가: apiUrl = `http://127.0.0.1:${api.address().port}`;
88추가: });
89추가:
90추가: after(async () => {
91추가: await new Promise((resolve) => api.close(resolve));
92추가: await rm(dir, { recursive: true, force: true });
93추가: });
94추가:
95추가: describe("gitgit-mcp", () => {
96추가: it("모든 도구를 등록하고 읽기 도구에 readOnlyHint 를 붙임", async () => {
97추가: const client = await connect();
98추가: const { tools } = await client.listTools();
99추가: const names = tools.map((tool) => tool.name);
100추가: for (const name of ["whoami", "get_repository", "read_file", "get_pull", "merge_pull", "create_issue", "upload_release_asset", "api_request"]) {
101추가: assert.ok(names.includes(name), name);
102추가: }
103추가: assert.equal(tools.find((tool) => tool.name === "read_file").annotations.readOnlyHint, true);
104추가: assert.equal(tools.find((tool) => tool.name === "merge_pull").annotations.destructiveHint, true);
105추가: assert.match(client.getInstructions(), /GitGit/);
106추가: await client.close();
107추가: });
108추가:
109추가: it("읽기 전용 모드에서는 쓰기 도구를 빼고 api_request 는 GET 만 받음", async () => {
110추가: const client = await connect({ GITGIT_READ_ONLY: "1" });
111추가: const names = (await client.listTools()).tools.map((tool) => tool.name);
112추가: assert.ok(names.includes("list_pulls"));
113추가: for (const name of ["create_issue", "merge_pull", "delete_release", "create_repository"]) assert.ok(!names.includes(name), name);
114추가: const denied = await client.callTool({ name: "api_request", arguments: { method: "POST", path: "/repositories" } });
115추가: assert.equal(denied.isError, true);
116추가: await client.close();
117추가: });
118추가:
119추가: it("토큰을 Bearer 헤더로 보내고 Origin 이나 쿠키는 보내지 않음", async () => {
120추가: const client = await connect();
121추가: const result = await call(client, "whoami");
122추가: assert.equal(result.error, false);
123추가: assert.match(result.text, /"authenticated": true/);
124추가: assert.equal(last().headers.authorization, `Bearer ${token}`);
125추가: assert.equal(last().headers.origin, undefined);
126추가: assert.equal(last().headers.cookie, undefined);
127추가: await client.close();
128추가: });
129추가:
130추가: it("사용자가 없으면 조직 저장소 목록으로 다시 찾음", async () => {
131추가: const client = await connect();
132추가: const result = await call(client, "list_repositories", { owner: "team", limit: 5 });
133추가: assert.equal(result.error, false);
134추가: assert.equal(last().path, "/api/v1/organizations/team/repositories");
135추가: assert.deepEqual(last().query, { limit: "5" });
136추가: await client.close();
137추가: });
138추가:
139추가: it("read_file 은 요청한 줄만 줄 번호와 함께 돌려줌", async () => {
140추가: const client = await connect();
141추가: const result = await call(client, "read_file", { owner: "alice", repo: "app", path: "a.txt", startLine: 2, endLine: 3, lineNumbers: true });
142추가: assert.equal(result.error, false);
143추가: assert.match(result.text, /lines 2-3 of 5/);
144추가: assert.match(result.text, /2\ttwo\n3\tthree$/);
145추가: assert.deepEqual(last().query, { path: "a.txt" });
146추가: await client.close();
147추가: });
148추가:
149추가: it("get_pull 은 PR 과 OID, Diff 본문 없는 파일 목록을 합침", async () => {
150추가: const client = await connect();
151추가: const result = await call(client, "get_pull", { owner: "alice", repo: "app", number: 7 });
152추가: const data = JSON.parse(result.text);
153추가: assert.equal(data.headOid, headOid);
154추가: assert.equal(data.baseOid, baseOid);
155추가: assert.equal(data.files.length, 2);
156추가: assert.equal(data.files[0].patch, undefined);
157추가: const diff = JSON.parse((await call(client, "get_pull_diff", { owner: "alice", repo: "app", number: 7, paths: ["docs/"] })).text);
158추가: assert.deepEqual(diff.diff.files.map((file) => file.path), ["docs/b.md"]);
159추가: await client.close();
160추가: });
161추가:
162추가: it("리뷰와 줄 댓글은 headOid 를 채워 anchor 를 만듦", async () => {
163추가: const client = await connect();
164추가: await call(client, "submit_pull_review", {
165추가: owner: "alice", repo: "app", number: 7, state: "approved", body: "LGTM",
166추가: comments: [{ body: "좋아요", path: "src/a.ts", line: 1 }],
167추가: });
168추가: assert.deepEqual(last().body, {
169추가: state: "approved", headOid, body: "LGTM",
170추가: comments: [{ body: "좋아요", anchor: { commitOid: headOid, path: "src/a.ts", side: "new", line: 1 } }],
171추가: });
172추가: await call(client, "create_pull_comment", { owner: "alice", repo: "app", number: 7, body: "여기", path: "src/a.ts", line: 1, side: "old" });
173추가: assert.deepEqual(last().body, { body: "여기", anchor: { commitOid: headOid, path: "src/a.ts", side: "old", line: 1 } });
174추가: const partial = await call(client, "create_pull_comment", { owner: "alice", repo: "app", number: 7, body: "x", path: "src/a.ts" });
175추가: assert.equal(partial.error, true);
176추가: await client.close();
177추가: });
178추가:
179추가: it("merge_pull 은 확인한 OID 를 그대로 보내고, 빠지면 거부함", async () => {
180추가: const client = await connect();
181추가: const missing = await client.callTool({ name: "merge_pull", arguments: { owner: "alice", repo: "app", number: 7 } });
182추가: assert.equal(missing.isError, true);
183추가: await call(client, "merge_pull", { owner: "alice", repo: "app", number: 7, method: "squash", expectedBaseOid: baseOid, expectedHeadOid: headOid });
184추가: assert.deepEqual(last().body, { method: "squash", expectedBaseOid: baseOid, expectedHeadOid: headOid });
185추가: await client.close();
186추가: });
187추가:
188추가: it("update_issue 는 준 필드만 보내고 assignee null 을 유지함", async () => {
189추가: const client = await connect();
190추가: await call(client, "update_issue", { owner: "alice", repo: "app", number: 3, state: "closed", assignee: null });
191추가: assert.equal(last().method, "PATCH");
192추가: assert.deepEqual(last().body, { state: "closed", assignee: null });
193추가: await client.close();
194추가: });
195추가:
196추가: it("슬래시가 있는 태그와 Asset 업로드 경로를 만듦", async () => {
197추가: const client = await connect();
198추가: await call(client, "get_release", { owner: "alice", repo: "app", tag: "release/v1" });
199추가: assert.equal(last().path, "/api/v1/repositories/alice/app/releases/tags/release/v1");
200추가: const file = join(dir, "out.zip");
201추가: await writeFile(file, "PK-test");
202추가: const uploaded = await call(client, "upload_release_asset", { owner: "alice", repo: "app", id: "00000000-0000-4000-8000-000000000001", filePath: file });
203추가: assert.equal(uploaded.error, false, uploaded.text);
204추가: assert.match(last().headers["content-type"], /^multipart\/form-data; boundary=/);
205추가: assert.match(last().body, /filename="out\.zip"/);
206추가: assert.match(last().body, /Content-Type: application\/zip/);
207추가: assert.match(last().body, /PK-test/);
208추가: await client.close();
209추가: });
210추가:
211추가: it("API 오류 코드와 안내를 isError 결과로 돌려줌", async () => {
212추가: const client = await connect();
213추가: const result = await call(client, "get_repository", { owner: "alice", repo: "private" });
214추가: assert.equal(result.error, true);
215추가: assert.match(result.text, /HTTP 403 INSUFFICIENT_SCOPE/);
216추가: assert.match(result.text, /범위/);
217추가: await client.close();
218추가: });
219추가:
220추가: it("api_request 는 /api/v1 밖으로 나가는 경로를 거부함", async () => {
221추가: const client = await connect();
222추가: for (const path of ["/../internal/overview", "//evil.example/x", "/repositories?x=1"]) {
223추가: const result = await client.callTool({ name: "api_request", arguments: { path } });
224추가: assert.equal(result.isError, true, path);
225추가: }
226추가: const before = requests.length;
227추가: assert.equal(requests.length, before);
228추가: await client.close();
229추가: });
230추가:
231추가: it("토큰 파일이 없으면 익명으로 시작하고 whoami 에 경고를 보여 줌", async () => {
232추가: const client = await connect({ GITGIT_TOKEN: "", GITGIT_TOKEN_FILE: join(dir, "missing-token") });
233추가: const result = JSON.parse((await call(client, "whoami")).text);
234추가: assert.equal(result.authenticated, false);
235추가: assert.match(result.warnings[0], /missing-token/);
236추가: assert.equal(last().headers.authorization, undefined);
237추가: await client.close();
238추가: });
239추가:
240추가: it("토큰 파일의 토큰을 씀", async () => {
241추가: const file = join(dir, "token");
242추가: await writeFile(file, token + "\n");
243추가: const client = await connect({ GITGIT_TOKEN: "", GITGIT_TOKEN_FILE: file });
244추가: await call(client, "whoami");
245추가: assert.equal(last().headers.authorization, `Bearer ${token}`);
246추가: await client.close();
247추가: });
248추가:
249추가: it("잘못된 토큰 형식이면 시작하지 않음", async () => {
250추가: await assert.rejects(connect({ GITGIT_TOKEN: "not-a-token" }));
251추가: });
252추가: });
추가tsconfig.json+17-0
@@ -0,0 +1,17 @@
1추가: {
2추가: "compilerOptions": {
3추가: "target": "ES2023",
4추가: "module": "NodeNext",
5추가: "moduleResolution": "NodeNext",
6추가: "rootDir": "src",
7추가: "outDir": "dist",
8추가: "strict": true,
9추가: "skipLibCheck": true,
10추가: "rewriteRelativeImportExtensions": true,
11추가: "allowImportingTsExtensions": true,
12추가: "verbatimModuleSyntax": true,
13추가: "erasableSyntaxOnly": true,
14추가: "types": ["node"]
15추가: },
16추가: "include": ["src"]
17추가: }