leejunyoung5819 gitgit-mcp
공개gitgit.kr MCP 도구
| 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 | }); |