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| @@ -0,0 +1,3 @@ | ||
| 1 | 추가: node_modules/ | |
| 2 | 추가: dist/ | |
| 3 | 추가: *.log |
| @@ -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 를 부르는지와 읽기 전용 모드, 오류 변환, 경로 제한을 확인합니다. |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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); |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
| @@ -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 | 추가: }); |
| @@ -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 | 추가: } |