@yoonion/mimi-seed-mcp 0.25.2 → 0.25.3

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.
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { catalog } from '#core/lang.js';
3
+ import { approvalMode, clientCanElicit, requestHumanApproval } from './human-approval.js';
3
4
  /** 자체 확인 파라미터 이름 — manifest `ownGate` 도구는 이 중 하나를 스키마에 가져야 한다. */
4
5
  export const CONFIRM_KEYS = ['confirm', 'confirmPublish', 'confirmVisible'];
5
6
  /** 레지스트라가 주입한 가드의 preview 첫 줄. 테스트와 에이전트가 이 문자열로 dry-run 을 식별한다. */
@@ -16,6 +17,7 @@ export function buildToolIndex(manifest) {
16
17
  const local = new Set(entry.local ?? []);
17
18
  const idempotent = new Set(entry.idempotent ?? []);
18
19
  const ownGate = new Set(entry.ownGate ?? []);
20
+ const approval = new Set(entry.approval ?? []);
19
21
  for (const name of entry.tools) {
20
22
  const kind = destructive.has(name) ? 'destructive' : write.has(name) ? 'write' : 'read';
21
23
  index.set(name, {
@@ -25,6 +27,7 @@ export function buildToolIndex(manifest) {
25
27
  local: local.has(name),
26
28
  idempotent: kind === 'read' || idempotent.has(name),
27
29
  ownGate: ownGate.has(name),
30
+ approval: approval.has(name),
28
31
  deprecatedFor: manifest.deprecated?.[name],
29
32
  aliases: aliasesOf.get(name) ?? [],
30
33
  });
@@ -129,13 +132,60 @@ export function previewValue(key, value) {
129
132
  return 'undefined';
130
133
  return raw.length > 200 ? `${raw.slice(0, 200)}… (${P().chars(raw.length)})` : raw;
131
134
  }
135
+ /**
136
+ * 확인 플래그인가 — `confirm` 또는 `confirm` + 대문자로 시작하는 이름 (`confirmPublish`, `confirmCreate` …).
137
+ * 세 이름만 보던 시절 `confirmCreate` 같은 새 플래그가 승인 게이트를 조용히 비껴갔다. ownGate 선언 검사는
138
+ * 여전히 CONFIRM_KEYS 로 한다 (그 규칙은 파괴적 도구의 가드 모양에 대한 것).
139
+ */
140
+ export function isConfirmKey(key) {
141
+ return /^confirm(?:[A-Z]\w*)?$/.test(key);
142
+ }
143
+ /** 인자 → ` key: value` 줄 (비밀 키는 가리고, 확인 플래그 자체는 뺀다). 비면 빈 배열. */
144
+ export function previewArgLines(args) {
145
+ return Object.entries(args)
146
+ .filter(([k, v]) => !isConfirmKey(k) && v !== undefined)
147
+ .map(([k, v]) => ` ${k}: ${previewValue(k, v)}`);
148
+ }
149
+ /**
150
+ * 줄바꿈·제어 문자에 더해, 화면에서 안 보이거나 글자 순서를 뒤집는 문자(zero-width, bidi override/isolate, BOM,
151
+ * soft hyphen, 줄/문단 구분자)를 `\uXXXX` 로 보이게 만든다. JSON.stringify 는 U+0020 미만만 이스케이프한다.
152
+ */
153
+ const INVISIBLE = /[\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g;
154
+ const showInvisible = (s) => s.replace(INVISIBLE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
155
+ /** 승인 대화상자의 값 하나가 넘으면 가운데를 생략한다 — 앞 HEAD + 뒤 TAIL 은 항상 보인다. */
156
+ const APPROVAL_VALUE_MAX = 1500;
157
+ const APPROVAL_VALUE_HEAD = 1000;
158
+ const APPROVAL_VALUE_TAIL = 300;
159
+ /**
160
+ * 승인 대화상자용 인자 줄. dry-run preview 와 달리 **사람이 마지막으로 보는 화면**이라 모델이 고른 값으로
161
+ * 화면을 위조할 수 없어야 한다: 문자열은 JSON 리터럴로(따옴표 + `\n` 이스케이프 — 값 안의 줄바꿈으로 가짜
162
+ * `key: value` 줄이나 "검증됨" 문구를 만들 수 없다), 보이지 않는 문자는 `\uXXXX` 로, 긴 값은 앞뒤를 보이고
163
+ * 생략 사실과 길이를 밝힌다 (200자에서 자르던 시절엔 뒤쪽에 숨긴 URL·명령이 안 보였다).
164
+ */
165
+ export function approvalArgLines(args) {
166
+ let truncated = false;
167
+ const lines = Object.entries(args)
168
+ .filter(([k, v]) => !isConfirmKey(k) && v !== undefined)
169
+ .map(([k, v]) => {
170
+ if (SECRET_KEY.test(k))
171
+ return ` ${k}: (redacted)`;
172
+ let shown = showInvisible(JSON.stringify(redactNested(v)) ?? 'undefined');
173
+ if (shown.length > APPROVAL_VALUE_MAX) {
174
+ truncated = true;
175
+ const hidden = shown.length - APPROVAL_VALUE_HEAD - APPROVAL_VALUE_TAIL;
176
+ shown = `${shown.slice(0, APPROVAL_VALUE_HEAD)} …[${hidden}/${shown.length}]… ${shown.slice(-APPROVAL_VALUE_TAIL)}`;
177
+ }
178
+ return ` ${k}: ${shown}`;
179
+ });
180
+ return { lines, truncated };
181
+ }
132
182
  export function confirmPreview(name, args) {
133
- const entries = Object.entries(args).filter(([k, v]) => k !== 'confirm' && v !== undefined);
183
+ const argLines = previewArgLines(args);
134
184
  const lines = [
135
185
  `${CONFIRM_PREVIEW_MARKER} — ${P().notRun(name)}`,
136
186
  '',
137
187
  P().args,
138
- ...(entries.length ? entries.map(([k, v]) => ` ${k}: ${previewValue(k, v)}`) : [` ${P().none}`]),
188
+ ...(argLines.length ? argLines : [` ${P().none}`]),
139
189
  '',
140
190
  P().next,
141
191
  ];
@@ -147,6 +197,7 @@ export const GUARD_DESCRIPTION = '⚠️ 안전 가드: confirm 생략/false 면
147
197
  export const CONFIRM_PARAM_DESCRIPTION = 'true 명시 시에만 실제 실행. 생략/false 면 dry-run preview 만 반환 (비가역·공개 사고 차단).';
148
198
  export function createToolRegistrar(server, options) {
149
199
  const { manifest, toolsets } = options;
200
+ const env = options.env ?? process.env;
150
201
  const t = options.translate ?? ((text) => text);
151
202
  const index = buildToolIndex(manifest);
152
203
  const metaOf = (name) => {
@@ -164,6 +215,7 @@ export function createToolRegistrar(server, options) {
164
215
  return {
165
216
  toolsets,
166
217
  manifest,
218
+ approvalStatus: () => ({ mode: approvalMode(env), clientCanElicit: clientCanElicit(server) }),
167
219
  tool(name, description, shape, handler, outputSchema) {
168
220
  const meta = metaOf(name);
169
221
  if (meta.deprecatedFor) {
@@ -199,6 +251,23 @@ export function createToolRegistrar(server, options) {
199
251
  return run(args, extra);
200
252
  };
201
253
  }
254
+ // 사람 승인 게이트 — 확인 플래그(confirm* — isConfirmKey)를 가진 **모든** 도구(레지스트라 가드 · ownGate · 자체 확인을
255
+ // 가진 쓰기 도구)에서, 플래그가 true 로 온 호출만 실행 직전에 사용자에게 직접 묻는다. 플래그 없는 호출은 그대로.
256
+ // manifest `approval` 도구는 플래그와 무관하게 매 호출 묻는다 — 플래그 없는 경로가 위험한 도구
257
+ // (자격증명 목적지 변경 `*_save_config`, 새 id 로 비밀 업로드, 배포 워크플로 시작).
258
+ const confirmKeys = Object.keys(finalShape).filter(isConfirmKey);
259
+ if (meta.approval || confirmKeys.length > 0) {
260
+ const gated = finalHandler;
261
+ const title = annotationsFor(meta).title;
262
+ finalHandler = async (args, extra) => {
263
+ if (!meta.approval && !confirmKeys.some((k) => args[k] === true))
264
+ return gated(args, extra);
265
+ const signal = extra?.signal;
266
+ const { lines, truncated } = approvalArgLines(args);
267
+ const refusal = await requestHumanApproval(server, { name, title, args, argLines: lines, truncated }, { signal, mode: approvalMode(env) });
268
+ return refusal ?? gated(args, extra);
269
+ };
270
+ }
202
271
  register(meta, finalDescription, finalShape, finalHandler, outputSchema);
203
272
  for (const alias of meta.aliases) {
204
273
  const aliasMeta = metaOf(alias);
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import os from 'node:os';
3
- import { GOOGLE_PROFILE_ID, listGoogleProfiles, getAuthenticatedClient, getGoogleAuthAttempt } from '../auth/google-auth.js';
3
+ import { GOOGLE_PROFILE_ID, listGoogleProfiles, getAuthenticatedClient, getStoredCredentials, getGoogleAuthAttempt } from '../auth/google-auth.js';
4
4
  import { verifyYouTubeChannel, YOUTUBE_CHANNEL_ID } from '../auth/youtube-channel.js';
5
5
  import { z } from 'zod';
6
6
  import { androidPackageName } from '../lib/package-name.js';
@@ -26,6 +26,7 @@ import { resolveSocialConfigTarget } from '../social/profile-store.js';
26
26
  import { lookupProjectManifest, manifestServiceEntries, } from '#core/project-manifest.js';
27
27
  import { textResult } from '../lib/mcp-response.js';
28
28
  import { describeToolsets } from '../lib/toolsets.js';
29
+ import { describeApproval } from '../lib/human-approval.js';
29
30
  import { findInvalidJsonFiles } from '../lib/json-file.js';
30
31
  import { credentialStoreReport } from '#core/credential-store.js';
31
32
  import { catalog } from '#core/lang.js';
@@ -99,7 +100,7 @@ const A = catalog({
99
100
  reqHeader: (name) => `── ${name} 요구사항 (.mimi-seed.json) ─────────`,
100
101
  teamHint: [
101
102
  'ℹ️ 팀 공유가 목표라면, 각자 로컬 자격증명을 채우는 대신',
102
- ' 워크스페이스(https://mimi-seed.pryzm.gg) 초대 → PAT 발급 → 원격 MCP 연결도 가능.',
103
+ ' 자체 운영 워크스페이스 초대 → PAT 발급 → 원격 MCP 연결도 가능.',
103
104
  ],
104
105
  },
105
106
  // ── mimi_seed_auth_start ──
@@ -197,7 +198,7 @@ const A = catalog({
197
198
  reqHeader: (name) => `── ${name} requirements (.mimi-seed.json) ─────────`,
198
199
  teamHint: [
199
200
  'ℹ️ If the goal is team sharing, instead of each person filling in local credentials,',
200
- ' you can also use workspace (https://mimi-seed.pryzm.gg) invite → PAT issuance → remote MCP connection.',
201
+ ' you can also use a team-operated workspace invite → PAT issuance → remote MCP connection.',
201
202
  ],
202
203
  },
203
204
  start: {
@@ -332,6 +333,8 @@ export function registerAuthTools(server) {
332
333
  m.header(PKG_VERSION),
333
334
  // 도메인을 꺼 둔 서버에서 "도구가 없다" 를 연결 문제로 오해하지 않게 켜진 toolset 을 밝힌다.
334
335
  `🧰 Toolsets: ${describeToolsets(server.toolsets, server.manifest)}`,
336
+ // 승인 게이트가 이 클라이언트에서 실제로 동작하는지 — 설정만 보고는 알 수 없다 (클라이언트 지원에 달림).
337
+ `🛡️ Approval: ${describeApproval(server.approvalStatus())}`,
335
338
  '',
336
339
  ];
337
340
  // 1. Google OAuth
@@ -559,7 +562,7 @@ export function registerAuthTools(server) {
559
562
  let clientId;
560
563
  let clientSecret;
561
564
  try {
562
- ({ clientId, clientSecret } = await getMcpOAuthClient());
565
+ ({ clientId, clientSecret } = await getMcpOAuthClient(getStoredCredentials(profile)));
563
566
  }
564
567
  catch (e) {
565
568
  const p = classifyError(e, { phase: 'login' });
@@ -1,3 +1,4 @@
1
+ import { consoleUrl } from '#core/console-url.js';
1
2
  import os from 'node:os';
2
3
  import path from 'node:path';
3
4
  import { getAppStoreCredentials } from './appstore/auth.js';
@@ -26,7 +27,7 @@ const R = catalog({
26
27
  skippedHeader: (n) => `- 건너뜀: 등록되지 않은 패키지 ${n}개 (playstore_list_service_accounts 로 등록 목록 확인):`,
27
28
  oauthNotCopied: '- Google OAuth: 복사하지 않음 (원격 웹에서 별도 동의 필요)',
28
29
  previewOnly: '미리보기만 수행했습니다. 원격 저장은 confirm=true일 때만 실행됩니다.',
29
- noConfig: '원격 연결 정보가 없습니다. 먼저 `mimi-seed init`을 실행하세요.',
30
+ noConfig: '원격 연결 정보가 없습니다. 팀 콘솔의 MIMI_SEED_WEB_BASE를 설정하고 `mimi-seed init`을 실행하세요.',
30
31
  untrusted: (reason) => `원격 엔드포인트를 신뢰할 수 없어 전송하지 않았습니다: ${reason}`,
31
32
  failed: '실패',
32
33
  skippedResult: (name) => `- Play ${name}: 건너뜀 (등록되지 않은 패키지)`,
@@ -51,7 +52,7 @@ const R = catalog({
51
52
  skippedHeader: (n) => `- Skipped: ${n} unregistered package(s) (check the registered list with playstore_list_service_accounts):`,
52
53
  oauthNotCopied: '- Google OAuth: not copied (requires separate consent on the remote web)',
53
54
  previewOnly: 'Preview only. Remote storage runs only with confirm=true.',
54
- noConfig: 'No remote connection info. Run `mimi-seed init` first.',
55
+ noConfig: 'No remote connection info. Set MIMI_SEED_WEB_BASE to your team console and run `mimi-seed init`.',
55
56
  untrusted: (reason) => `The remote endpoint is not trusted, so nothing was sent: ${reason}`,
56
57
  failed: 'failed',
57
58
  skippedResult: (name) => `- Play ${name}: skipped (unregistered package)`,
@@ -61,7 +62,9 @@ const R = catalog({
61
62
  function getRemoteConfig() {
62
63
  const envToken = process.env.MIMI_SEED_TOKEN;
63
64
  if (envToken) {
64
- const webBase = process.env.MIMI_SEED_WEB_BASE ?? 'https://mimi-seed.pryzm.gg';
65
+ const webBase = consoleUrl(process.env.MIMI_SEED_WEB_BASE);
66
+ if (!webBase)
67
+ return null;
65
68
  return { token: envToken, endpoint: `${webBase}/api/mcp`, webBase };
66
69
  }
67
70
  try {
@@ -70,6 +73,8 @@ function getRemoteConfig() {
70
73
  if (!parsed.token || !parsed.endpoint)
71
74
  return null;
72
75
  const webBase = parsed.webBase ?? parsed.endpoint.replace(/\/api\/mcp\/?$/, '');
76
+ if (!consoleUrl(webBase) || !consoleUrl(parsed.endpoint))
77
+ return null;
73
78
  return { token: parsed.token, endpoint: parsed.endpoint, webBase };
74
79
  }
75
80
  catch {
package/dist/server.js CHANGED
@@ -48,6 +48,7 @@ export function buildServer(version, options = {}) {
48
48
  'If the user starts Mimi Seed without a specific task, show mimi-seed://tools/menu and let them choose one or more services by number, name, or free-form description. Read mimi-seed://tools/menu/{areas} for the selected comma-separated service IDs before loading tools for the task.',
49
49
  'For a targeted read, start with the domain tool. Use mimi_seed_status for onboarding, connection diagnostics, or unresolved authentication errors.',
50
50
  'For preview-gated writes, get the preview and explicit approval before confirming the same operation.',
51
+ 'A confirmed call may also open an approval dialog for the user; if it returns ⛔ (not approved), nothing changed — do not retry, ask the user.',
51
52
  ].join(' '),
52
53
  });
53
54
  // 도구는 McpServer 에 직접이 아니라 레지스트라를 거쳐 등록한다 — manifest(SSOT)에서
@@ -61,7 +62,7 @@ export function buildServer(version, options = {}) {
61
62
  // 원문은 한국어이고 en 이면 i18n/tools-en 번역표로 바꾼다 (lib/tool-text.ts). 서버 수명 동안 고정이다.
62
63
  const toolLang = options.lang ?? resolveLang();
63
64
  const translate = toolTextTranslator(toolLang);
64
- const registrar = createToolRegistrar(server, { manifest, toolsets, translate });
65
+ const registrar = createToolRegistrar(server, { manifest, toolsets, translate, env: options.env ?? process.env });
65
66
  registerFirebaseTools(registrar);
66
67
  registerAdmobTools(registrar);
67
68
  registerPlaystoreTools(registrar);
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { consoleUrl } from '#core/console-url.js';
2
3
  // mimi-seed-social-auth — Facebook 페이지 / Instagram 계정 연결.
3
4
  //
4
5
  // 검증·저장 구현은 facebook/setup.ts · instagram/setup.ts 에 있고, MCP 도구
@@ -67,9 +68,9 @@ const ko = {
67
68
  thNote: ' (Instagram 과 **별개 계정·별개 토큰**. userId 는 토큰에서 자동 조회돼. 수명 약 60일.)',
68
69
  thAskToken: ' Threads Access Token: ',
69
70
  thAskUserId: ' Threads user ID (선택, 엔터 시 자동 조회): ',
70
- thExistingAction: ' [Enter/y] 기존 토큰 자동 갱신 [r] 브라우저로 다시 로그인 [n] 건너뛰기: ',
71
+ thExistingAction: ' [Enter/y] 기존 토큰 자동 갱신 [r] 다시 연결 [n] 건너뛰기: ',
71
72
  thRefreshing: ' 🔄 기존 Threads 토큰 갱신 중...',
72
- thRefreshFallback: ' 자동 갱신에 실패했습니다. 브라우저 로그인으로 다시 연결합니다.',
73
+ thRefreshFallback: ' 자동 갱신에 실패했습니다. 다시 연결합니다.',
73
74
  profile: (id) => ` 소셜 프로필: ${id}`,
74
75
  invalidArgs: ' 사용법: mimi-seed-social-auth [facebook|instagram|threads|all] [--profile <id>] [--manual-token]',
75
76
  };
@@ -113,7 +114,7 @@ const en = {
113
114
  thNote: ' (A **separate account and token** from Instagram. userId is looked up from the token. ~60 days.)',
114
115
  thAskToken: ' Threads Access Token: ',
115
116
  thAskUserId: ' Threads user ID (optional, Enter to look it up): ',
116
- thExistingAction: ' [Enter/y] refresh current token [r] sign in again in your browser [n] skip: ',
117
+ thExistingAction: ' [Enter/y] refresh current token [r] reconnect [n] skip: ',
117
118
  thRefreshing: ' 🔄 Refreshing the existing Threads token...',
118
119
  thRefreshFallback: ' Automatic refresh failed. Reconnecting in your browser.',
119
120
  profile: (id) => ` Social profile: ${id}`,
@@ -182,7 +183,7 @@ async function setupInstagram(profile, manualToken = false) {
182
183
  if (existing && !(await confirmReconnect('Instagram', existing.username ?? existing.userId))) {
183
184
  return true;
184
185
  }
185
- if (!manualToken) {
186
+ if (!manualToken && consoleUrl(process.env.MIMI_SEED_WEB_BASE)) {
186
187
  console.log(M.igBrowser);
187
188
  try {
188
189
  const result = await connectInstagramInBrowser({ ...options, onUrl: (url) => { console.log(M.thUrl); console.log(url); console.log(M.thResume); } });
@@ -239,7 +240,7 @@ async function setupThreads(profile, manualToken = false) {
239
240
  console.log(M.thRefreshFallback);
240
241
  }
241
242
  }
242
- if (!manualToken) {
243
+ if (!manualToken && consoleUrl(process.env.MIMI_SEED_WEB_BASE)) {
243
244
  console.log(M.thBrowser);
244
245
  try {
245
246
  const result = await connectThreadsInBrowser({ ...options, onUrl: (url) => { console.log(M.thUrl); console.log(url); console.log(M.thResume); } });
@@ -1,3 +1,4 @@
1
+ import { consoleUrl } from '#core/console-url.js';
1
2
  import { createServer } from 'node:http';
2
3
  import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
3
4
  import { fetchWithTimeout } from '../lib/http.js';
@@ -16,7 +17,10 @@ export async function connectThreadsInBrowser(options = {}) {
16
17
  // Freeze the selected profile before any asynchronous work / directory changes.
17
18
  const target = resolveSocialConfigTarget('threads', options);
18
19
  const saveOptions = { ...options, profile: target.profile ?? undefined, startDir: options.startDir ?? process.cwd() };
19
- const base = new URL(options.webBase ?? process.env.MIMI_SEED_WEB_BASE ?? 'https://mimi-seed.pryzm.gg');
20
+ const url = consoleUrl(options.webBase ?? process.env.MIMI_SEED_WEB_BASE);
21
+ if (!url)
22
+ throw new ThreadsLoginError('configuration');
23
+ const base = new URL(url);
20
24
  if (base.protocol !== 'https:' || base.username || base.password || base.search || base.hash || base.pathname !== '/') {
21
25
  throw new ThreadsLoginError('configuration');
22
26
  }