@yoonion/mimi-seed-mcp 0.21.7 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,281 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { google } from '../lib/googleapis-lite.js';
5
+ import { mediaUploadOptions } from '../lib/google-timeouts.js';
6
+ import { authReauthMessage, extractHttpStatus, googleErrorDetail, rawMessage, withCause, } from '../lib/google-errors.js';
7
+ export const FOLDER_MIME = 'application/vnd.google-apps.folder';
8
+ const FIELDS = 'id,name,mimeType,size,md5Checksum,createdTime,modifiedTime,parents,driveId,trashed,webViewLink,description';
9
+ /**
10
+ * Drive 파일·폴더 ID. 영숫자·밑줄·하이픈만 허용한다 — 이 값은 files.list 의 q 문자열 안에
11
+ * 그대로 들어가므로, 따옴표가 섞이면 질의가 다른 뜻이 된다. 'root' 는 내 드라이브 최상위 별칭.
12
+ */
13
+ export const DRIVE_ID_RE = /^(root|[A-Za-z0-9_-]{10,200})$/;
14
+ function assertDriveId(id, what) {
15
+ if (!DRIVE_ID_RE.test(id))
16
+ throw new Error(`${what} 형식이 올바르지 않아: 영숫자·_·- 만 쓰는 Drive ID 여야 해.`);
17
+ }
18
+ /** files.list q 문자열 리터럴 이스케이프 (\ 와 ' ). */
19
+ export function escapeQueryValue(value) {
20
+ return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
21
+ }
22
+ function drive(auth) {
23
+ return google.drive({ version: 'v3', auth: auth });
24
+ }
25
+ function toFile(f) {
26
+ return {
27
+ id: f.id ?? '',
28
+ name: f.name ?? '',
29
+ mimeType: f.mimeType ?? '',
30
+ isFolder: f.mimeType === FOLDER_MIME,
31
+ size: f.size != null ? Number(f.size) : null,
32
+ md5Checksum: f.md5Checksum ?? null,
33
+ createdTime: f.createdTime ?? null,
34
+ modifiedTime: f.modifiedTime ?? null,
35
+ parents: f.parents ?? [],
36
+ driveId: f.driveId ?? null,
37
+ trashed: f.trashed === true,
38
+ webViewLink: f.webViewLink ?? null,
39
+ description: f.description ?? null,
40
+ };
41
+ }
42
+ /**
43
+ * Drive 에러를 "무엇을 고칠지"가 보이는 메시지로. 서비스 계정과 OAuth(drive.file) 는
44
+ * 같은 404 라도 원인이 달라 안내를 나눈다.
45
+ */
46
+ export function driveError(e, source, clientEmail) {
47
+ const text = rawMessage(e);
48
+ const detail = googleErrorDetail(e);
49
+ const status = extractHttpStatus(e);
50
+ const both = `${text} ${detail ?? ''}`;
51
+ const tail = detail && !text.includes(detail) ? `\nGoogle API: ${detail}` : `\nGoogle API: ${text}`;
52
+ const isSa = source === 'service-account' || source === 'service-account-env';
53
+ const reauth = authReauthMessage(both);
54
+ if (reauth && !isSa)
55
+ return withCause(new Error(reauth), e);
56
+ if (/storageQuotaExceeded|do not have storage quota/i.test(both)) {
57
+ return withCause(new Error([
58
+ '❌ 서비스 계정은 자기 저장 공간이 없어서 "내 드라이브"에는 파일을 만들 수 없어.',
59
+ '→ 공유 드라이브 안의 폴더에 올리거나(서비스 계정을 공유 드라이브 멤버로 추가),',
60
+ ' 사용자 OAuth(mimi-seed-auth --domains drive)를 써.',
61
+ ].join('\n') + tail), e);
62
+ }
63
+ if (status === 404 || /notFound|File not found/i.test(both)) {
64
+ const lines = isSa
65
+ ? [
66
+ `❌ 파일·폴더를 찾을 수 없어 — 없거나 서비스 계정${clientEmail ? `(${clientEmail})` : ''}과 공유되지 않았어.`,
67
+ '→ Drive 에서 대상 폴더(또는 공유 드라이브)를 이 서비스 계정 이메일과 공유해 (편집자 이상).',
68
+ ]
69
+ : [
70
+ '❌ 파일·폴더를 찾을 수 없어.',
71
+ '→ OAuth(drive.file) 권한은 mimi-seed 가 만든 파일·폴더만 볼 수 있어.',
72
+ ' 기존 폴더를 다루려면 Drive 서비스 계정을 써: npx -y @yoonion/mimi-seed-mcp mimi-seed-drive-auth',
73
+ ];
74
+ return withCause(new Error(lines.join('\n') + tail), e);
75
+ }
76
+ if (status === 403 || /insufficientFilePermissions|forbidden|permission/i.test(both)) {
77
+ return withCause(new Error([
78
+ '❌ 이 파일·폴더에 쓸 권한이 없어.',
79
+ isSa
80
+ ? '→ 폴더 공유 권한을 "편집자"(공유 드라이브는 "콘텐츠 관리자") 이상으로 올려.'
81
+ : '→ 이 Google 계정의 권한을 확인하거나 Drive 서비스 계정을 써.',
82
+ ].join('\n') + tail), e);
83
+ }
84
+ return withCause(new Error(`❌ Google Drive 오류: ${text}${detail && !text.includes(detail) ? `\nGoogle API: ${detail}` : ''}`), e);
85
+ }
86
+ /** files.list 의 q 문자열 조립 (테스트가 이스케이프를 고정한다). */
87
+ export function buildListQuery(input) {
88
+ const q = [];
89
+ if (input.folderId) {
90
+ assertDriveId(input.folderId, 'folderId');
91
+ q.push(`'${input.folderId}' in parents`);
92
+ }
93
+ if (input.nameContains)
94
+ q.push(`name contains '${escapeQueryValue(input.nameContains)}'`);
95
+ if (input.mimeType)
96
+ q.push(`mimeType = '${escapeQueryValue(input.mimeType)}'`);
97
+ if (!input.includeTrashed)
98
+ q.push('trashed = false');
99
+ return q.join(' and ');
100
+ }
101
+ export async function listFiles(auth, input) {
102
+ const pageSize = Math.min(Math.max(Math.trunc(input.pageSize ?? 100), 1), 1000);
103
+ const res = await drive(auth).files.list({
104
+ q: buildListQuery(input) || undefined,
105
+ pageSize,
106
+ pageToken: input.pageToken,
107
+ orderBy: 'folder,name',
108
+ fields: `nextPageToken, files(${FIELDS})`,
109
+ supportsAllDrives: true,
110
+ includeItemsFromAllDrives: true,
111
+ corpora: 'allDrives',
112
+ });
113
+ return { files: (res.data.files ?? []).map(toFile), nextPageToken: res.data.nextPageToken ?? null };
114
+ }
115
+ export async function getFile(auth, fileId) {
116
+ assertDriveId(fileId, 'fileId');
117
+ const res = await drive(auth).files.get({ fileId, fields: FIELDS, supportsAllDrives: true });
118
+ return toFile(res.data);
119
+ }
120
+ /** 부모 폴더 안에서 이름이 정확히 같은 항목(휴지통 제외). 폴더만 찾을지 선택. */
121
+ async function findChildByName(auth, parentId, name, kind) {
122
+ const mime = kind === 'folder' ? `mimeType = '${FOLDER_MIME}'` : `mimeType != '${FOLDER_MIME}'`;
123
+ const res = await drive(auth).files.list({
124
+ q: `'${parentId}' in parents and name = '${escapeQueryValue(name)}' and ${mime} and trashed = false`,
125
+ pageSize: 2,
126
+ fields: `files(${FIELDS})`,
127
+ supportsAllDrives: true,
128
+ includeItemsFromAllDrives: true,
129
+ corpora: 'allDrives',
130
+ });
131
+ const hit = res.data.files?.[0];
132
+ return hit ? toFile(hit) : null;
133
+ }
134
+ function cleanName(name, what) {
135
+ const trimmed = name.trim();
136
+ if (!trimmed)
137
+ throw new Error(`${what} 이 비어 있어.`);
138
+ if (trimmed.length > 255)
139
+ throw new Error(`${what} 은 255자 이하여야 해.`);
140
+ return trimmed;
141
+ }
142
+ export async function createFolder(auth, input) {
143
+ const name = cleanName(input.name, '폴더 이름');
144
+ const parentId = input.parentId ?? 'root';
145
+ assertDriveId(parentId, 'parentId');
146
+ if (input.reuseExisting !== false) {
147
+ const existing = await findChildByName(auth, parentId, name, 'folder');
148
+ if (existing)
149
+ return { status: 'exists', folder: existing };
150
+ }
151
+ const res = await drive(auth).files.create({
152
+ requestBody: { name, mimeType: FOLDER_MIME, parents: [parentId] },
153
+ fields: FIELDS,
154
+ supportsAllDrives: true,
155
+ });
156
+ return { status: 'created', folder: toFile(res.data) };
157
+ }
158
+ const MIME_BY_EXT = {
159
+ '.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.mkv': 'video/x-matroska',
160
+ '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.wav': 'audio/wav', '.ogg': 'audio/ogg',
161
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
162
+ '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.zip': 'application/zip', '.json': 'application/json',
163
+ '.txt': 'text/plain', '.md': 'text/markdown', '.csv': 'text/csv', '.html': 'text/html',
164
+ '.srt': 'application/x-subrip', '.vtt': 'text/vtt',
165
+ };
166
+ /** 확장자 → MIME. 모르면 application/octet-stream (Drive 가 Google 문서로 변환하지 않는다). */
167
+ export function guessMimeType(filePath) {
168
+ return MIME_BY_EXT[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
169
+ }
170
+ /** 업로드할 로컬 파일 점검 — 절대 경로, 일반 파일, 비어 있지 않음. */
171
+ export function inspectLocalFile(filePath, mimeType) {
172
+ if (!path.isAbsolute(filePath))
173
+ throw new Error('filePath 는 절대 경로여야 해.');
174
+ let size;
175
+ try {
176
+ const stat = statSync(filePath);
177
+ if (!stat.isFile())
178
+ throw new Error('not-a-file');
179
+ size = stat.size;
180
+ }
181
+ catch (e) {
182
+ if (e instanceof Error && e.message === 'not-a-file')
183
+ throw new Error(`파일이 아니야: ${filePath}`, { cause: e });
184
+ throw new Error(`파일을 읽을 수 없어: ${filePath}`, { cause: e });
185
+ }
186
+ if (size === 0)
187
+ throw new Error(`빈 파일은 올리지 않아: ${filePath}`);
188
+ return { path: filePath, size, mimeType: mimeType ?? guessMimeType(filePath) };
189
+ }
190
+ /** 로컬 파일 MD5 — 업로드 결과의 md5Checksum 과 비교해 전송 무결성을 확인한다. */
191
+ export function md5OfFile(filePath) {
192
+ return new Promise((resolve, reject) => {
193
+ const hash = createHash('md5');
194
+ createReadStream(filePath)
195
+ .on('data', (chunk) => hash.update(chunk))
196
+ .on('error', reject)
197
+ .on('end', () => resolve(hash.digest('hex')));
198
+ });
199
+ }
200
+ async function verified(local, remote) {
201
+ if (!remote.md5Checksum)
202
+ return null; // Google 문서 형식 등은 체크섬이 없다
203
+ return (await md5OfFile(local.path)) === remote.md5Checksum;
204
+ }
205
+ export async function uploadFile(auth, input) {
206
+ const local = inspectLocalFile(input.filePath, input.mimeType);
207
+ const name = cleanName(input.name ?? path.basename(input.filePath), '파일 이름');
208
+ const parentId = input.parentId ?? 'root';
209
+ assertDriveId(parentId, 'parentId');
210
+ if (input.onConflict !== 'create_new') {
211
+ const existing = await findChildByName(auth, parentId, name, 'file');
212
+ if (existing) {
213
+ throw new Error(`같은 폴더에 "${name}" 이 이미 있어 (fileId ${existing.id}). ` +
214
+ '내용을 바꾸려면 drive_update_file_content, 하나 더 만들려면 onConflict="create_new".');
215
+ }
216
+ }
217
+ const res = await drive(auth).files.create({
218
+ requestBody: { name, parents: [parentId] },
219
+ media: { mimeType: local.mimeType, body: createReadStream(local.path) },
220
+ fields: FIELDS,
221
+ supportsAllDrives: true,
222
+ }, mediaUploadOptions());
223
+ const file = toFile(res.data);
224
+ return { status: 'uploaded', file, local, verified: await verified(local, file) };
225
+ }
226
+ /** 기존 파일의 내용을 로컬 파일로 교체 (같은 fileId·링크 유지, Drive 가 이전 버전을 보관). */
227
+ export async function updateFileContent(auth, input) {
228
+ const local = inspectLocalFile(input.filePath, input.mimeType);
229
+ const before = await getFile(auth, input.fileId);
230
+ if (before.isFolder)
231
+ throw new Error('폴더에는 내용을 올릴 수 없어.');
232
+ const res = await drive(auth).files.update({
233
+ fileId: input.fileId,
234
+ media: { mimeType: local.mimeType, body: createReadStream(local.path) },
235
+ fields: FIELDS,
236
+ supportsAllDrives: true,
237
+ }, mediaUploadOptions());
238
+ const after = toFile(res.data);
239
+ return { status: 'updated', before, after, local, verified: await verified(local, after) };
240
+ }
241
+ /** 이름·설명 변경, 다른 폴더로 이동. 하나 이상 바꿔야 한다. */
242
+ export async function updateFileMetadata(auth, input) {
243
+ if (input.name === undefined && input.description === undefined && input.moveToFolderId === undefined) {
244
+ throw new Error('바꿀 항목(name, description, moveToFolderId)이 하나도 없어.');
245
+ }
246
+ const before = await getFile(auth, input.fileId);
247
+ let addParents;
248
+ let removeParents;
249
+ if (input.moveToFolderId !== undefined) {
250
+ assertDriveId(input.moveToFolderId, 'moveToFolderId');
251
+ if (!before.parents.includes(input.moveToFolderId)) {
252
+ addParents = input.moveToFolderId;
253
+ removeParents = before.parents.join(',') || undefined;
254
+ }
255
+ }
256
+ const requestBody = {};
257
+ if (input.name !== undefined)
258
+ requestBody.name = cleanName(input.name, '파일 이름');
259
+ if (input.description !== undefined)
260
+ requestBody.description = input.description;
261
+ const res = await drive(auth).files.update({
262
+ fileId: input.fileId,
263
+ requestBody,
264
+ addParents,
265
+ removeParents,
266
+ fields: FIELDS,
267
+ supportsAllDrives: true,
268
+ });
269
+ return { status: 'updated', before, after: toFile(res.data) };
270
+ }
271
+ /** 휴지통으로 이동 (30일 안에는 Drive 휴지통에서 되살릴 수 있다). */
272
+ export async function trashFile(auth, fileId) {
273
+ const before = await getFile(auth, fileId);
274
+ const res = await drive(auth).files.update({
275
+ fileId,
276
+ requestBody: { trashed: true },
277
+ fields: FIELDS,
278
+ supportsAllDrives: true,
279
+ });
280
+ return { status: 'trashed', before, after: toFile(res.data) };
281
+ }
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ const SUBCOMMANDS = {
14
14
  'mimi-seed-playstore-auth': () => import('./auth/playstore-setup-cli.js'),
15
15
  'mimi-seed-appstore-auth': () => import('./appstore/setup-cli.js'),
16
16
  'mimi-seed-bigquery-auth': () => import('./auth/bigquery-setup-cli.js'),
17
+ 'mimi-seed-drive-auth': () => import('./auth/drive-setup-cli.js'),
17
18
  'mimi-seed-jenkins-auth': () => import('./jenkins/setup-cli.js'),
18
19
  'mimi-seed-googleads-auth': () => import('./googleads/setup-cli.js'),
19
20
  'mimi-seed-social-auth': () => import('./social/setup-cli.js'),
@@ -23,6 +24,13 @@ const SUBCOMMANDS = {
23
24
  'mimi-seed-ga4': () => import('./ga4/cli.js'),
24
25
  'mimi-seed-release-doctor': () => import('./checks/release-doctor-cli.js'),
25
26
  };
27
+ const USAGE = [
28
+ 'Subcommands:',
29
+ ...Object.keys(SUBCOMMANDS).map((k) => ` npx -y @yoonion/mimi-seed-mcp ${k}`),
30
+ '',
31
+ 'Or run the MCP server (no args) — normally started by an MCP client such as Claude Code or Codex:',
32
+ ' npx -y @yoonion/mimi-seed-mcp',
33
+ ].join('\n');
26
34
  async function main() {
27
35
  const sub = process.argv[2];
28
36
  if (sub && SUBCOMMANDS[sub]) {
@@ -31,18 +39,24 @@ async function main() {
31
39
  await SUBCOMMANDS[sub]();
32
40
  return;
33
41
  }
42
+ // 플래그는 서버 기동으로 흘려보내면 stdin 대기로 멈춘 것처럼 보인다 — 바로 답하고 끝낸다.
43
+ if (sub === '--version' || sub === '-v') {
44
+ console.log(version);
45
+ return;
46
+ }
47
+ if (sub === '--help' || sub === '-h') {
48
+ console.log(`mimi-seed-mcp ${version}\n\n${USAGE}`);
49
+ return;
50
+ }
34
51
  if (sub && !sub.startsWith('-')) {
35
- console.error([
36
- `❌ Unknown subcommand: ${sub}`,
37
- '',
38
- 'Available:',
39
- ...Object.keys(SUBCOMMANDS).map((k) => ` npx -y @yoonion/mimi-seed-mcp ${k}`),
40
- '',
41
- 'Or run the MCP server (no args):',
42
- ' npx -y @yoonion/mimi-seed-mcp',
43
- ].join('\n'));
52
+ console.error(`❌ Unknown subcommand: ${sub}\n\n${USAGE}`);
44
53
  process.exit(2);
45
54
  }
55
+ // 사람이 터미널에서 직접 띄운 경우에만 안내한다. stdout 은 MCP 프로토콜 전용이라 stderr 로.
56
+ if (process.stdin.isTTY) {
57
+ console.error(`mimi-seed-mcp ${version}: MCP server running on stdio, waiting for an MCP client. ` +
58
+ 'It is not interactive — press Ctrl+C to exit. Run with --help for subcommands.');
59
+ }
46
60
  const server = buildServer(version);
47
61
  const transport = new StdioServerTransport();
48
62
  await server.connect(transport);
@@ -1,22 +1,14 @@
1
1
  import { z } from 'zod';
2
2
  import type { JenkinsConfig } from './config.js';
3
- export declare const buildJobSchema: z.ZodEffects<z.ZodString, string, string>;
3
+ export declare const buildJobSchema: z.ZodString;
4
4
  export declare const buildIdSchema: z.ZodNumber;
5
5
  export declare const requestIdSchema: z.ZodString;
6
6
  export declare const buildParametersSchema: z.ZodRecord<z.ZodString, z.ZodString>;
7
7
  export declare const triggerBuildSchema: z.ZodObject<{
8
- job: z.ZodEffects<z.ZodString, string, string>;
8
+ job: z.ZodString;
9
9
  request_id: z.ZodString;
10
10
  parameters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
11
- }, "strip", z.ZodTypeAny, {
12
- job: string;
13
- request_id: string;
14
- parameters?: Record<string, string> | undefined;
15
- }, {
16
- job: string;
17
- request_id: string;
18
- parameters?: Record<string, string> | undefined;
19
- }>;
11
+ }, z.core.$strip>;
20
12
  type TriggerInput = z.infer<typeof triggerBuildSchema>;
21
13
  /**
22
14
  * 예약이 이보다 젊으면 결과가 없는 재호출을 `pending`(다른 호출이 처리 중)으로, 더 오래됐으면 `unknown`
@@ -81,10 +73,10 @@ export declare function getBuildStatus(cfg: JenkinsConfig, job: string, buildNum
81
73
  build_url: string;
82
74
  } | {
83
75
  number: number;
84
- result: "SUCCESS" | "FAILURE" | "UNSTABLE" | "ABORTED" | "NOT_BUILT" | null;
85
76
  building: boolean;
86
- duration?: number | undefined;
77
+ result: "SUCCESS" | "FAILURE" | "UNSTABLE" | "ABORTED" | "NOT_BUILT" | null;
87
78
  timestamp?: number | undefined;
79
+ duration?: number | undefined;
88
80
  job: string;
89
81
  build_number: number;
90
82
  build_url: string;
@@ -1,4 +1,5 @@
1
1
  export type { youtube_v3 } from 'googleapis/build/src/apis/youtube/index.js';
2
+ export type { drive_v3 } from 'googleapis/build/src/apis/drive/index.js';
2
3
  export type { youtubeAnalytics_v2 } from 'googleapis/build/src/apis/youtubeAnalytics/index.js';
3
4
  /**
4
5
  * 기존 `google.<api>(...)` 호출부와 100% 동일하게 동작하는 지연 로딩 네임스페이스.
@@ -21,6 +22,7 @@ export declare const google: {
21
22
  readonly analyticsadmin: typeof import("googleapis/build/src/apis/analyticsadmin/index.js").analyticsadmin;
22
23
  readonly analyticsdata: typeof import("googleapis/build/src/apis/analyticsdata/index.js").analyticsdata;
23
24
  readonly androidpublisher: typeof import("googleapis/build/src/apis/androidpublisher/index.js").androidpublisher;
25
+ readonly drive: typeof import("googleapis/build/src/apis/drive/index.js").drive;
24
26
  readonly bigquery: typeof import("googleapis/build/src/apis/bigquery/index.js").bigquery;
25
27
  readonly billingbudgets: typeof import("googleapis/build/src/apis/billingbudgets/index.js").billingbudgets;
26
28
  readonly cloudbilling: typeof import("googleapis/build/src/apis/cloudbilling/index.js").cloudbilling;
@@ -67,6 +67,9 @@ export const google = {
67
67
  get androidpublisher() {
68
68
  return sub('androidpublisher').androidpublisher;
69
69
  },
70
+ get drive() {
71
+ return sub('drive').drive;
72
+ },
70
73
  get bigquery() {
71
74
  return sub('bigquery').bigquery;
72
75
  },
@@ -46,7 +46,7 @@ export function registerCiTools(server) {
46
46
  ].join(' '), {
47
47
  ref: z.string().default('main').describe('브랜치 또는 태그 (기본: main)'),
48
48
  workflow: z.string().optional().describe('GitHub 전용: 워크플로 파일명 또는 ID (예: deploy.yml)'),
49
- inputs: z.record(z.string()).optional().describe('워크플로 입력값 (GitHub inputs / GitLab variables)'),
49
+ inputs: z.record(z.string(), z.string()).optional().describe('워크플로 입력값 (GitHub inputs / GitLab variables)'),
50
50
  }, async ({ ref, workflow, inputs }) => {
51
51
  const cfg = requireCiConfig();
52
52
  let result;
@@ -0,0 +1,2 @@
1
+ import type { ToolRegistrar } from '../lib/tool-registrar.js';
2
+ export declare function registerDriveTools(server: ToolRegistrar): void;
@@ -0,0 +1,108 @@
1
+ import { z } from 'zod';
2
+ import { GOOGLE_PROFILE_ID, getStoredTokens } from '../auth/google-auth.js';
3
+ import { DRIVE_FILE_SCOPE } from '../auth/scopes.js';
4
+ import { DRIVE_AUTH_HINT, driveJwt, getDriveServiceAccount } from '../auth/drive-auth.js';
5
+ import { requireAuth } from '../helpers.js';
6
+ import { jsonResult, errorResult } from '../lib/mcp-response.js';
7
+ import * as drive from '../drive/tools.js';
8
+ /**
9
+ * Drive 인증 해석: Drive 서비스 계정(환경 변수 > 파일)이 있으면 그것, 없으면 Google OAuth(drive.file).
10
+ * 서비스 계정은 공유받은 기존 폴더·공유 드라이브를 다룰 수 있고, OAuth drive.file 은
11
+ * mimi-seed 가 만든 파일·폴더만 다룬다.
12
+ */
13
+ async function resolveDriveAuth(profile) {
14
+ const sa = getDriveServiceAccount();
15
+ if (sa)
16
+ return { client: driveJwt(sa.key), source: sa.source, clientEmail: sa.key.client_email ?? null };
17
+ if (!getStoredTokens(profile))
18
+ throw new Error(DRIVE_AUTH_HINT);
19
+ return { client: await requireAuth(DRIVE_FILE_SCOPE, profile), source: 'user-oauth', clientEmail: null };
20
+ }
21
+ /** 인증 → 호출 → JSON. Drive 오류는 driveError 로 원인별 안내를 붙인다. */
22
+ async function withDrive(profile, run) {
23
+ let auth;
24
+ try {
25
+ auth = await resolveDriveAuth(profile);
26
+ }
27
+ catch (e) {
28
+ return errorResult(e instanceof Error ? e.message : String(e));
29
+ }
30
+ try {
31
+ return jsonResult({ authSource: auth.source, ...(await run(auth.client)) });
32
+ }
33
+ catch (e) {
34
+ return errorResult(drive.driveError(e, auth.source, auth.clientEmail).message);
35
+ }
36
+ }
37
+ const profile = z.string().regex(GOOGLE_PROFILE_ID).optional()
38
+ .describe('Google 로그인 프로필 (OAuth 사용 시). Drive 서비스 계정이 설정돼 있으면 무시된다.');
39
+ const driveId = (what) => z.string().regex(drive.DRIVE_ID_RE).describe(what);
40
+ const absPath = z.string().min(1).describe('올릴 로컬 파일의 절대 경로');
41
+ export function registerDriveTools(server) {
42
+ server.tool('drive_auth_status', '현재 Google Drive 인증 상태 — Drive 서비스 계정(환경 변수/파일) 또는 Google OAuth(drive.file) 중 무엇이 쓰이는지 확인', { profile }, async ({ profile }) => {
43
+ try {
44
+ const sa = getDriveServiceAccount();
45
+ if (sa) {
46
+ return jsonResult({
47
+ authenticated: true,
48
+ source: sa.source,
49
+ clientEmail: sa.key.client_email,
50
+ note: '대상 폴더나 공유 드라이브를 이 이메일과 공유해야 접근할 수 있다.',
51
+ });
52
+ }
53
+ }
54
+ catch (e) {
55
+ return errorResult(e instanceof Error ? e.message : String(e));
56
+ }
57
+ const granted = getStoredTokens(profile)?.scope?.split(' ') ?? null;
58
+ if (granted?.includes(DRIVE_FILE_SCOPE)) {
59
+ return jsonResult({
60
+ authenticated: true,
61
+ source: 'user-oauth',
62
+ scope: DRIVE_FILE_SCOPE,
63
+ note: 'drive.file 권한은 mimi-seed 가 만든 파일·폴더만 다룬다. 기존 폴더는 Drive 서비스 계정을 쓴다.',
64
+ });
65
+ }
66
+ return jsonResult({ authenticated: false, hint: DRIVE_AUTH_HINT });
67
+ });
68
+ server.tool('drive_list_files', 'Google Drive 파일·폴더 목록 조회 — 폴더 ID, 이름 일부, MIME 형식으로 거른다. 공유 드라이브 포함, 기본으로 휴지통 제외.', {
69
+ folderId: driveId('이 폴더 바로 아래만 조회 (폴더 ID 또는 "root")').optional(),
70
+ nameContains: z.string().max(255).optional().describe('이름에 포함된 문자열'),
71
+ mimeType: z.string().max(255).optional().describe('MIME 형식 일치 (폴더는 application/vnd.google-apps.folder)'),
72
+ includeTrashed: z.boolean().optional().describe('휴지통 항목 포함 (기본 false)'),
73
+ pageSize: z.number().int().min(1).max(1000).optional().describe('페이지 크기 (기본 100)'),
74
+ pageToken: z.string().optional().describe('이전 응답의 nextPageToken'),
75
+ profile,
76
+ }, async ({ profile, ...input }) => withDrive(profile, (c) => drive.listFiles(c, input)));
77
+ server.tool('drive_get_file', 'Google Drive 파일·폴더 하나의 메타데이터(이름, MIME, 크기, MD5, 부모, 링크, 수정 시각) 조회', { fileId: driveId('파일 또는 폴더 ID'), profile }, async ({ fileId, profile }) => withDrive(profile, async (c) => ({ file: await drive.getFile(c, fileId) })));
78
+ server.tool('drive_create_folder', 'Google Drive 폴더 생성. 부모 안에 같은 이름의 폴더가 이미 있으면 새로 만들지 않고 그 폴더를 돌려준다(status=exists).', {
79
+ name: z.string().min(1).max(255).describe('폴더 이름'),
80
+ parentId: driveId('부모 폴더 ID (기본 "root" — 내 드라이브 최상위)').optional(),
81
+ reuseExisting: z.boolean().optional().describe('같은 이름 폴더 재사용 (기본 true). false 면 항상 새로 만든다.'),
82
+ profile,
83
+ }, async ({ profile, ...input }) => withDrive(profile, (c) => drive.createFolder(c, input)));
84
+ server.tool('drive_upload_file', '로컬 파일을 Google Drive 폴더에 새 파일로 업로드 (재개 가능 업로드, 완료 후 MD5 대조). ' +
85
+ '같은 폴더에 같은 이름이 있으면 기본으로 거부한다 — 내용 교체는 drive_update_file_content.', {
86
+ filePath: absPath,
87
+ parentId: driveId('올릴 폴더 ID (기본 "root")').optional(),
88
+ name: z.string().min(1).max(255).optional().describe('Drive 에서 쓸 이름 (기본: 로컬 파일 이름)'),
89
+ mimeType: z.string().max(255).optional().describe('MIME 형식 (기본: 확장자로 추정)'),
90
+ onConflict: z.enum(['error', 'create_new']).optional()
91
+ .describe('같은 이름이 있을 때: error(기본) 또는 create_new(하나 더 만든다)'),
92
+ profile,
93
+ }, async ({ profile, ...input }) => withDrive(profile, (c) => drive.uploadFile(c, input)));
94
+ server.tool('drive_update_file_content', '기존 Drive 파일의 내용을 로컬 파일로 교체 — 같은 fileId·공유 링크를 유지하고, Drive 가 이전 버전을 버전 기록에 보관한다. 완료 후 MD5 대조.', {
95
+ fileId: driveId('내용을 바꿀 파일 ID'),
96
+ filePath: absPath,
97
+ mimeType: z.string().max(255).optional().describe('MIME 형식 (기본: 확장자로 추정)'),
98
+ profile,
99
+ }, async ({ profile, ...input }) => withDrive(profile, (c) => drive.updateFileContent(c, input)));
100
+ server.tool('drive_update_file_metadata', 'Drive 파일·폴더의 이름·설명 변경 또는 다른 폴더로 이동. 하나 이상 지정해야 한다.', {
101
+ fileId: driveId('대상 파일 또는 폴더 ID'),
102
+ name: z.string().min(1).max(255).optional().describe('새 이름'),
103
+ description: z.string().max(4000).optional().describe('새 설명'),
104
+ moveToFolderId: driveId('옮겨 갈 폴더 ID').optional(),
105
+ profile,
106
+ }, async ({ profile, ...input }) => withDrive(profile, (c) => drive.updateFileMetadata(c, input)));
107
+ server.tool('drive_trash_file', 'Drive 파일·폴더를 휴지통으로 이동 (영구 삭제 아님 — Drive 휴지통에서 30일 안에 되살릴 수 있다).', { fileId: driveId('휴지통으로 보낼 파일 또는 폴더 ID'), profile }, async ({ fileId, profile }) => withDrive(profile, (c) => drive.trashFile(c, fileId)));
108
+ }
@@ -18,6 +18,7 @@ export function registerVideoTools(server) {
18
18
  '로컬 영상 파일을 선택한 Google 로그인 프로필의 채널에 업로드합니다. expectedChannelId를 실제 인증 채널과 대조한 후 전송합니다.',
19
19
  '기본 공개 상태는 private이며 public/unlisted는 같은 턴의 명시 승인 후 confirmVisible=true가 필요합니다.',
20
20
  '업로드 후 youtube_get_video_status로 처리 완료 여부와 실제 공개 상태를 확인하세요.',
21
+ 'Studio 업로드 기본값은 API 업로드에 적용되지 않습니다. 카테고리·제목/설명 언어·실제 음성 언어를 지정하세요. 댓글 검토 필터는 API로 설정하거나 확인할 수 없어 Studio 검증이 필요합니다.',
21
22
  '요청이 타임아웃되면 업로드가 뒤늦게 완료될 수 있으므로 YouTube Studio를 먼저 확인하고 중복 재시도하지 마세요.',
22
23
  'YouTube OAuth 권한이 없으면 mimi_seed_auth_start(domains=["youtube"])로 증분 연결하세요.',
23
24
  ].join(' '), {
@@ -28,6 +29,8 @@ export function registerVideoTools(server) {
28
29
  description: z.string().max(5_000).optional().describe('영상 설명과 음원 출처/라이선스 표기'),
29
30
  tags: z.array(z.string().min(1).max(500)).max(100).optional(),
30
31
  categoryId: z.string().regex(/^\d+$/).default('24').describe('YouTube 카테고리 ID'),
32
+ defaultLanguage: z.string().min(2).max(35).optional().describe('제목·설명의 BCP-47 언어 코드 (예: ko, en). 음성 언어와 별개입니다.'),
33
+ defaultAudioLanguage: z.string().min(2).max(35).optional().describe('실제 음성의 BCP-47 언어 코드 (예: ko, en). 무대사는 생략하고 비공개 업로드 후 Studio에서 동영상 언어를 해당 사항 없음으로 저장·확인하세요. 제목으로 추정하지 않습니다.'),
31
34
  privacyStatus: z.enum(['private', 'unlisted', 'public']).default('private'),
32
35
  madeForKids: z.boolean().default(false),
33
36
  containsSyntheticMedia: z.boolean().optional().describe('현실적으로 보이는 AI 생성·변형 콘텐츠 여부를 YouTube에 고지'),
@@ -38,7 +41,7 @@ export function registerVideoTools(server) {
38
41
  const auth = await requireAuth(YOUTUBE_SCOPE, input.profile);
39
42
  return jsonResult(await uploadYouTubeVideo(auth, input));
40
43
  });
41
- server.tool('youtube_get_video_status', '내 YouTube 영상의 업로드 처리 상태와 현재 공개 상태를 조회합니다.', {
44
+ server.tool('youtube_get_video_status', '내 YouTube 영상의 처리·공개 상태와 실제 반환된 카테고리·제목/설명 언어·음성 언어를 조회합니다. null은 미확인이며 무대사 판정이 아닙니다. 댓글 검토 필터는 Studio에서 별도로 확인해야 합니다.', {
42
45
  profile: z.string().regex(GOOGLE_PROFILE_ID).optional().describe('영상 소유 채널의 Google 로그인 프로필'),
43
46
  videoId: z.string().min(1).max(64).describe('YouTube video ID'),
44
47
  }, async ({ videoId, profile }) => {
package/dist/server.js CHANGED
@@ -22,6 +22,7 @@ import { registerAndroidTools } from './registers/android.js';
22
22
  import { registerVideoTools } from './registers/video.js';
23
23
  import { registerYouTubeTools } from './registers/youtube.js';
24
24
  import { registerTikTokBusinessTools } from './registers/tiktok.js';
25
+ import { registerDriveTools } from './registers/drive.js';
25
26
  import { registerPrompts } from './prompts.js';
26
27
  import { registerResources } from './resources.js';
27
28
  import { readToolManifest } from './lib/package-root.js';
@@ -71,6 +72,7 @@ export function buildServer(version, options = {}) {
71
72
  registerVideoTools(registrar);
72
73
  registerYouTubeTools(registrar);
73
74
  registerTikTokBusinessTools(registrar);
75
+ registerDriveTools(registrar);
74
76
  registerPrompts(server);
75
77
  registerResources(server, { manifest, toolsets });
76
78
  return server;
@@ -3,64 +3,22 @@ declare const briefSchema: z.ZodObject<{
3
3
  summary: z.ZodString;
4
4
  patterns: z.ZodArray<z.ZodObject<{
5
5
  pattern: z.ZodString;
6
- evidence: z.ZodArray<z.ZodString, "many">;
7
- confidence: z.ZodEnum<["low", "medium", "high"]>;
8
- }, "strip", z.ZodTypeAny, {
9
- pattern: string;
10
- evidence: string[];
11
- confidence: "high" | "low" | "medium";
12
- }, {
13
- pattern: string;
14
- evidence: string[];
15
- confidence: "high" | "low" | "medium";
16
- }>, "many">;
6
+ evidence: z.ZodArray<z.ZodString>;
7
+ confidence: z.ZodEnum<{
8
+ high: "high";
9
+ low: "low";
10
+ medium: "medium";
11
+ }>;
12
+ }, z.core.$strip>>;
17
13
  recommendations: z.ZodArray<z.ZodObject<{
18
14
  sceneId: z.ZodOptional<z.ZodString>;
19
15
  action: z.ZodString;
20
16
  rationale: z.ZodString;
21
- }, "strip", z.ZodTypeAny, {
22
- action: string;
23
- rationale: string;
24
- sceneId?: string | undefined;
25
- }, {
26
- action: string;
27
- rationale: string;
28
- sceneId?: string | undefined;
29
- }>, "many">;
30
- avoidCopying: z.ZodArray<z.ZodString, "many">;
31
- referenceUrls: z.ZodArray<z.ZodString, "many">;
32
- limitations: z.ZodArray<z.ZodString, "many">;
33
- }, "strip", z.ZodTypeAny, {
34
- summary: string;
35
- patterns: {
36
- pattern: string;
37
- evidence: string[];
38
- confidence: "high" | "low" | "medium";
39
- }[];
40
- recommendations: {
41
- action: string;
42
- rationale: string;
43
- sceneId?: string | undefined;
44
- }[];
45
- avoidCopying: string[];
46
- referenceUrls: string[];
47
- limitations: string[];
48
- }, {
49
- summary: string;
50
- patterns: {
51
- pattern: string;
52
- evidence: string[];
53
- confidence: "high" | "low" | "medium";
54
- }[];
55
- recommendations: {
56
- action: string;
57
- rationale: string;
58
- sceneId?: string | undefined;
59
- }[];
60
- avoidCopying: string[];
61
- referenceUrls: string[];
62
- limitations: string[];
63
- }>;
17
+ }, z.core.$strip>>;
18
+ avoidCopying: z.ZodArray<z.ZodString>;
19
+ referenceUrls: z.ZodArray<z.ZodString>;
20
+ limitations: z.ZodArray<z.ZodString>;
21
+ }, z.core.$strip>;
64
22
  export interface ReferenceObservation {
65
23
  referenceUrl: string;
66
24
  notes: string;