leejunyoung5819gitgit-mcp

공개

gitgit.kr MCP 도구

150줄8.7 KB
1import { z } from "zod";
2import { repositoryPath, segment } from "../client.ts";
3import { cursor, limit, oid, owner, ref, repo, type Registrar } from "../tooling.ts";
4
5type FileView = { file: { path: string; oid: string; size: number; status: "text" | "binary" | "too_large"; content: string | null; rawUrl: string } };
6type DiffFile = { path: string; change: string; status: string; patch: string | null };
7
8const path = z.string().min(1).max(4096).describe("저장소 루트 기준 파일 경로. 예: src/index.ts");
9// too_large 파일을 Raw 로 다시 받을 때의 상한. 이보다 크면 메타데이터만 돌려줌
10const rawFallbackBytes = 5 * 1024 * 1024;
11
12function 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
23export 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
33export const diffPaths = z.array(z.string().min(1).max(4096)).max(200).optional()
34 .describe("이 경로의 파일만 돌려줍니다. / 로 끝나면 그 폴더 아래 전체");
35
36export 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}