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