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