@yoonion/mimi-seed-mcp 0.23.4 → 0.24.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.
@@ -54,6 +54,11 @@ export declare const AUTH_DOMAINS: {
54
54
  readonly scopes: readonly ["https://www.googleapis.com/auth/webmasters"];
55
55
  readonly summary: "gsc_* — 사이트·사이트맵·검색 성과 (사이트맵 제출 포함)";
56
56
  };
57
+ readonly gsc_readonly: {
58
+ readonly label: "Search Console (read-only)";
59
+ readonly scopes: readonly ["https://www.googleapis.com/auth/webmasters.readonly"];
60
+ readonly summary: "사이트·사이트맵·URL 색인 상태·검색 성과 조회";
61
+ };
57
62
  readonly ga4: {
58
63
  readonly label: "Google Analytics (GA4)";
59
64
  readonly scopes: readonly ["https://www.googleapis.com/auth/analytics.edit", "https://www.googleapis.com/auth/analytics.readonly"];
@@ -79,6 +84,9 @@ export type AuthDomainId = keyof typeof AUTH_DOMAINS;
79
84
  /** z.enum 등 튜플이 필요한 자리에 쓰는 도메인 id 목록 (선언 순서 유지). */
80
85
  export declare const DOMAIN_IDS: [AuthDomainId, ...AuthDomainId[]];
81
86
  export declare const CLOUD_PLATFORM_SCOPE: "https://www.googleapis.com/auth/cloud-platform";
87
+ export declare const GSC_WRITE_SCOPE: "https://www.googleapis.com/auth/webmasters";
88
+ export declare const GSC_READONLY_SCOPE: "https://www.googleapis.com/auth/webmasters.readonly";
89
+ export declare const GSC_READ_SCOPES: readonly ["https://www.googleapis.com/auth/webmasters.readonly", "https://www.googleapis.com/auth/webmasters"];
82
90
  /** Drive OAuth 경로가 pre-flight 하는 스코프. 도메인 정의에서 파생한다(리터럴 중복 금지). */
83
91
  export declare const DRIVE_FILE_SCOPE: "https://www.googleapis.com/auth/drive.file";
84
92
  /**
@@ -56,6 +56,11 @@ export const AUTH_DOMAINS = {
56
56
  scopes: ['https://www.googleapis.com/auth/webmasters'],
57
57
  summary: 'gsc_* — 사이트·사이트맵·검색 성과 (사이트맵 제출 포함)',
58
58
  },
59
+ gsc_readonly: {
60
+ label: 'Search Console (read-only)',
61
+ scopes: ['https://www.googleapis.com/auth/webmasters.readonly'],
62
+ summary: '사이트·사이트맵·URL 색인 상태·검색 성과 조회',
63
+ },
59
64
  ga4: {
60
65
  label: 'Google Analytics (GA4)',
61
66
  scopes: [
@@ -92,6 +97,9 @@ export const AUTH_DOMAINS = {
92
97
  /** z.enum 등 튜플이 필요한 자리에 쓰는 도메인 id 목록 (선언 순서 유지). */
93
98
  export const DOMAIN_IDS = Object.keys(AUTH_DOMAINS);
94
99
  export const CLOUD_PLATFORM_SCOPE = AUTH_DOMAINS.gcp.scopes[0];
100
+ export const GSC_WRITE_SCOPE = AUTH_DOMAINS.gsc.scopes[0];
101
+ export const GSC_READONLY_SCOPE = AUTH_DOMAINS.gsc_readonly.scopes[0];
102
+ export const GSC_READ_SCOPES = [GSC_READONLY_SCOPE, GSC_WRITE_SCOPE];
95
103
  /** Drive OAuth 경로가 pre-flight 하는 스코프. 도메인 정의에서 파생한다(리터럴 중복 금지). */
96
104
  export const DRIVE_FILE_SCOPE = AUTH_DOMAINS.drive.scopes[0];
97
105
  /**
@@ -104,8 +112,10 @@ export const DRIVE_FILE_SCOPE = AUTH_DOMAINS.drive.scopes[0];
104
112
  * 죽는 함정이 된다. auth-scopes.test.ts 가 값과 도메인 포함 여부를 함께 고정한다.
105
113
  */
106
114
  export const PLAY_DEVELOPER_REPORTING_SCOPE = AUTH_DOMAINS.playstore.scopes[1];
107
- function dedupe(scopes) {
108
- return [...new Set(scopes)];
115
+ function requestedScopes(domains) {
116
+ const scopes = [...new Set(domains.flatMap((id) => AUTH_DOMAINS[id].scopes))];
117
+ // webmasters already authorizes all Search Console reads.
118
+ return scopes.includes(GSC_WRITE_SCOPE) ? scopes.filter((scope) => scope !== GSC_READONLY_SCOPE) : scopes;
109
119
  }
110
120
  /**
111
121
  * 공백 구분 scope 문자열들의 합집합. tokens.json 의 scope 는 누적(monotonic)이어야 하므로
@@ -127,7 +137,7 @@ export function mergeScopeStrings(...parts) {
127
137
  * 도메인 미지정 로그인의 기본값이자, 선택형 도입 전 full-scope 목록과 동일해야 한다
128
138
  * (auth-scopes.test.ts 가 고정한다 — 스코프가 소리 없이 빠지면 기존 사용자 도구가 죽는다).
129
139
  */
130
- export const ALL_SCOPES = dedupe(DOMAIN_IDS.flatMap((id) => AUTH_DOMAINS[id].scopes));
140
+ export const ALL_SCOPES = requestedScopes(DOMAIN_IDS);
131
141
  /**
132
142
  * 모든 로그인에 함께 싣는 계정 식별 스코프 (비민감 — 동의 화면에 "이메일 주소 보기"만 추가).
133
143
  *
@@ -142,7 +152,7 @@ export const IDENTITY_SCOPES = ['openid', 'https://www.googleapis.com/auth/useri
142
152
  export function scopesForDomains(domains) {
143
153
  if (!domains || domains.length === 0)
144
154
  return [...ALL_SCOPES];
145
- return dedupe(domains.flatMap((id) => AUTH_DOMAINS[id].scopes));
155
+ return requestedScopes(domains);
146
156
  }
147
157
  /** 스코프 하나를 요구하는 도메인들 (INSUFFICIENT_SCOPE 안내에서 "--domains X" 를 채울 때 사용). */
148
158
  export function domainsForScope(scope) {
@@ -169,6 +179,8 @@ export function summarizeGrantedDomains(scopeStr) {
169
179
  if (scopeStr === undefined)
170
180
  return { known: false, granted: [], missing: [] };
171
181
  const grantedScopes = new Set(scopeStr.split(' ').filter(Boolean));
182
+ if (grantedScopes.has(GSC_WRITE_SCOPE))
183
+ grantedScopes.add(GSC_READONLY_SCOPE);
172
184
  const granted = [];
173
185
  const missing = [];
174
186
  for (const id of DOMAIN_IDS) {
@@ -1,23 +1,129 @@
1
1
  import type { OAuth2Client } from 'google-auth-library';
2
+ import type { searchconsole_v1 } from '@googleapis/searchconsole';
2
3
  export type GscAuth = OAuth2Client;
3
- export declare function listSites(auth: GscAuth): Promise<import("@googleapis/searchconsole").searchconsole_v1.Schema$WmxSite[]>;
4
- export declare function listSitemaps(auth: GscAuth, siteUrl: string, sitemapIndex?: string): Promise<import("@googleapis/searchconsole").searchconsole_v1.Schema$WmxSitemap[]>;
5
- export declare function getSitemap(auth: GscAuth, siteUrl: string, feedpath: string): Promise<import("@googleapis/searchconsole").searchconsole_v1.Schema$WmxSitemap>;
4
+ export declare function listSites(auth: GscAuth): Promise<searchconsole_v1.Schema$WmxSite[]>;
5
+ export declare function listSitemaps(auth: GscAuth, siteUrl: string, sitemapIndex?: string): Promise<(searchconsole_v1.Schema$WmxSitemap | {
6
+ contents: {
7
+ submitted?: string | null;
8
+ type?: string | null;
9
+ }[];
10
+ errors?: string | null;
11
+ isPending?: boolean | null;
12
+ isSitemapsIndex?: boolean | null;
13
+ lastDownloaded?: string | null;
14
+ lastSubmitted?: string | null;
15
+ path?: string | null;
16
+ type?: string | null;
17
+ warnings?: string | null;
18
+ })[]>;
19
+ export declare function getSitemap(auth: GscAuth, siteUrl: string, feedpath: string): Promise<searchconsole_v1.Schema$WmxSitemap | {
20
+ contents: {
21
+ submitted?: string | null;
22
+ type?: string | null;
23
+ }[];
24
+ errors?: string | null;
25
+ isPending?: boolean | null;
26
+ isSitemapsIndex?: boolean | null;
27
+ lastDownloaded?: string | null;
28
+ lastSubmitted?: string | null;
29
+ path?: string | null;
30
+ type?: string | null;
31
+ warnings?: string | null;
32
+ }>;
6
33
  /** 사이트맵 제출 — webmasters(read-write) 스코프 필요. 응답 본문은 없음(204). */
7
34
  export declare function submitSitemap(auth: GscAuth, siteUrl: string, feedpath: string): Promise<{
8
35
  submitted: string;
9
36
  siteUrl: string;
10
37
  }>;
11
- export declare function inspectUrl(auth: GscAuth, siteUrl: string, inspectionUrl: string, languageCode?: string): Promise<import("@googleapis/searchconsole").searchconsole_v1.Schema$UrlInspectionResult>;
12
- export interface SearchAnalyticsParams {
38
+ export declare function inspectUrl(auth: GscAuth, siteUrl: string, inspectionUrl: string, languageCode?: string): Promise<searchconsole_v1.Schema$UrlInspectionResult>;
39
+ export declare const SEARCH_TYPES: readonly ["web", "image", "video", "news", "discover", "googleNews"];
40
+ export declare const SEARCH_FILTER_DIMENSIONS: readonly ["page", "query", "country", "device", "searchAppearance", "brandedClassification"];
41
+ export declare const SEARCH_FILTER_OPERATORS: readonly ["equals", "notEquals", "contains", "notContains", "includingRegex", "excludingRegex"];
42
+ interface SearchAnalyticsFilter {
43
+ dimension: (typeof SEARCH_FILTER_DIMENSIONS)[number];
44
+ operator?: (typeof SEARCH_FILTER_OPERATORS)[number];
45
+ expression: string;
46
+ }
47
+ interface SearchAnalyticsParams {
13
48
  startDate: string;
14
49
  endDate: string;
15
- dimensions?: string[];
50
+ dimensions?: string;
16
51
  rowLimit?: number;
17
52
  startRow?: number;
18
- type?: 'web' | 'image' | 'video' | 'news' | 'discover' | 'googleNews';
53
+ type?: (typeof SEARCH_TYPES)[number];
54
+ filters?: SearchAnalyticsFilter[];
55
+ summaryOnly?: boolean;
56
+ includeTotals?: boolean;
19
57
  }
20
- export declare function searchAnalytics(auth: GscAuth, siteUrl: string, params: SearchAnalyticsParams): Promise<import("@googleapis/searchconsole").searchconsole_v1.Schema$ApiDataRow[]>;
58
+ export declare function searchAnalytics(auth: GscAuth, siteUrl: string, params: SearchAnalyticsParams): Promise<{
59
+ aggregationType: string | null;
60
+ rowSummary: {
61
+ rowCount: number;
62
+ totalClicks: number;
63
+ totalImpressions: number;
64
+ avgCtr: number;
65
+ avgPosition: number | null;
66
+ };
67
+ pagination: {
68
+ startRow: number;
69
+ rowLimit: number;
70
+ nextStartRow: number | null;
71
+ mayOmitRows: boolean;
72
+ };
73
+ rows: searchconsole_v1.Schema$ApiDataRow[];
74
+ period: {
75
+ startDate: string;
76
+ endDate: string;
77
+ };
78
+ type: "web" | "video" | "image" | "news" | "discover" | "googleNews";
79
+ dimensions: string[];
80
+ } | {
81
+ rows?: searchconsole_v1.Schema$ApiDataRow[] | undefined;
82
+ aggregationType: string | null;
83
+ summary: {
84
+ rowCount: number;
85
+ totalClicks: number;
86
+ totalImpressions: number;
87
+ avgCtr: number;
88
+ avgPosition: number | null;
89
+ };
90
+ period: {
91
+ startDate: string;
92
+ endDate: string;
93
+ };
94
+ type: "web" | "video" | "image" | "news" | "discover" | "googleNews";
95
+ dimensions: string[];
96
+ } | {
97
+ summary: {
98
+ rowCount: number;
99
+ totalClicks: number;
100
+ totalImpressions: number;
101
+ avgCtr: number;
102
+ avgPosition: number | null;
103
+ };
104
+ totalAggregationType: string | null;
105
+ aggregationType: string | null;
106
+ rowSummary: {
107
+ rowCount: number;
108
+ totalClicks: number;
109
+ totalImpressions: number;
110
+ avgCtr: number;
111
+ avgPosition: number | null;
112
+ };
113
+ pagination: {
114
+ startRow: number;
115
+ rowLimit: number;
116
+ nextStartRow: number | null;
117
+ mayOmitRows: boolean;
118
+ };
119
+ rows: searchconsole_v1.Schema$ApiDataRow[];
120
+ period: {
121
+ startDate: string;
122
+ endDate: string;
123
+ };
124
+ type: "web" | "video" | "image" | "news" | "discover" | "googleNews";
125
+ dimensions: string[];
126
+ }>;
21
127
  export interface SearchAnalyticsRow {
22
128
  keys?: string[] | null;
23
129
  clicks?: number | null;
@@ -35,5 +141,6 @@ export declare function summarizeRows(rows: SearchAnalyticsRow[]): {
35
141
  totalClicks: number;
36
142
  totalImpressions: number;
37
143
  avgCtr: number;
38
- avgPosition: number;
144
+ avgPosition: number | null;
39
145
  };
146
+ export {};
package/dist/gsc/tools.js CHANGED
@@ -5,7 +5,7 @@ import { notDotSegment } from '../lib/resource-id.js';
5
5
  *
6
6
  * `searchconsole('v1')` 은 구 `webmasters('v3')` 의 후속으로, sites/sitemaps/
7
7
  * searchanalytics 에 더해 URL Inspection(`urlInspection.index.inspect`)을 포함한다.
8
- * 인증은 mimi-seed OAuth 클라이언트(`requireAuth()`)를 그대로 사용 — webmasters 스코프 필요.
8
+ * 조회에는 webmasters.readonly 또는 webmasters, 사이트맵 제출에는 webmasters를 사용한다.
9
9
  */
10
10
  const sc = () => google.searchconsole('v1');
11
11
  // ─── 속성(사이트) 목록 ───
@@ -14,15 +14,20 @@ export async function listSites(auth) {
14
14
  return res.data.siteEntry ?? [];
15
15
  }
16
16
  // ─── 사이트맵 ───
17
+ function withoutIndexedCount(sitemap) {
18
+ if (!sitemap.contents)
19
+ return sitemap;
20
+ return { ...sitemap, contents: sitemap.contents.map(({ indexed: _indexed, ...content }) => content) };
21
+ }
17
22
  export async function listSitemaps(auth, siteUrl, sitemapIndex) {
18
23
  const res = await sc().sitemaps.list({ auth, siteUrl: notDotSegment(siteUrl, 'siteUrl'), sitemapIndex });
19
- return res.data.sitemap ?? [];
24
+ return (res.data.sitemap ?? []).map(withoutIndexedCount);
20
25
  }
21
26
  export async function getSitemap(auth, siteUrl, feedpath) {
22
27
  const res = await sc().sitemaps.get({
23
28
  auth, siteUrl: notDotSegment(siteUrl, 'siteUrl'), feedpath: notDotSegment(feedpath, 'feedpath'),
24
29
  });
25
- return res.data;
30
+ return withoutIndexedCount(res.data);
26
31
  }
27
32
  /** 사이트맵 제출 — webmasters(read-write) 스코프 필요. 응답 본문은 없음(204). */
28
33
  export async function submitSitemap(auth, siteUrl, feedpath) {
@@ -39,20 +44,79 @@ export async function inspectUrl(auth, siteUrl, inspectionUrl, languageCode = 'e
39
44
  });
40
45
  return res.data.inspectionResult ?? {};
41
46
  }
42
- export async function searchAnalytics(auth, siteUrl, params) {
47
+ // ─── 검색 성과 (Search Analytics) ───
48
+ export const SEARCH_TYPES = ['web', 'image', 'video', 'news', 'discover', 'googleNews'];
49
+ export const SEARCH_FILTER_DIMENSIONS = ['page', 'query', 'country', 'device', 'searchAppearance', 'brandedClassification'];
50
+ export const SEARCH_FILTER_OPERATORS = ['equals', 'notEquals', 'contains', 'notContains', 'includingRegex', 'excludingRegex'];
51
+ async function querySearchAnalytics(auth, siteUrl, requestBody) {
43
52
  const res = await sc().searchanalytics.query({
44
53
  auth,
45
- siteUrl: notDotSegment(siteUrl, 'siteUrl'),
46
- requestBody: {
47
- startDate: params.startDate,
48
- endDate: params.endDate,
49
- dimensions: params.dimensions,
50
- rowLimit: params.rowLimit ?? 1000,
51
- startRow: params.startRow,
52
- type: params.type,
54
+ siteUrl,
55
+ requestBody,
56
+ });
57
+ const rows = res.data.rows ?? [];
58
+ // Discover and the Google News app/site don't report position. Google can return a zero placeholder.
59
+ const hasPosition = requestBody.type !== 'discover' && requestBody.type !== 'googleNews';
60
+ return {
61
+ rows: hasPosition ? rows : rows.map((row) => ({ ...row, position: null })),
62
+ aggregationType: res.data.responseAggregationType ?? null,
63
+ };
64
+ }
65
+ export async function searchAnalytics(auth, siteUrl, params) {
66
+ const { startDate, endDate, startRow = 0, rowLimit = 1000, type = 'web', filters, summaryOnly, includeTotals } = params;
67
+ if (startDate > endDate)
68
+ throw new Error('startDate는 endDate 이전 또는 같은 날짜여야 해.');
69
+ const dimensions = params.dimensions?.split(',').map((value) => value.trim()).filter(Boolean) ?? [];
70
+ const reportDimensions = summaryOnly ? [] : dimensions;
71
+ if (startRow > 0 && reportDimensions.length === 0 && !summaryOnly) {
72
+ throw new Error('startRow는 dimensions로 분해한 조회에만 사용할 수 있어.');
73
+ }
74
+ const property = notDotSegment(siteUrl, 'siteUrl');
75
+ const period = { startDate, endDate };
76
+ const request = {
77
+ ...period,
78
+ type,
79
+ dimensionFilterGroups: filters?.length
80
+ ? [{ groupType: 'and', filters: filters.map((filter) => ({ ...filter, operator: filter.operator ?? 'equals' })) }]
81
+ : undefined,
82
+ };
83
+ const report = { period, type, dimensions: reportDimensions };
84
+ if (reportDimensions.length === 0) {
85
+ const { rows, aggregationType } = await querySearchAnalytics(auth, property, { ...request, rowLimit: 1 });
86
+ return { ...report, aggregationType, summary: summarizeRows(rows), ...(summaryOnly ? {} : { rows }) };
87
+ }
88
+ const { rows, aggregationType } = await querySearchAnalytics(auth, property, {
89
+ ...request, dimensions: reportDimensions, rowLimit, startRow,
90
+ });
91
+ const page = {
92
+ ...report,
93
+ aggregationType,
94
+ rowSummary: summarizeRows(rows),
95
+ pagination: {
96
+ startRow,
97
+ rowLimit,
98
+ nextStartRow: rows.length === rowLimit ? startRow + rows.length : null,
99
+ mayOmitRows: true,
53
100
  },
101
+ rows,
102
+ };
103
+ if (!includeTotals)
104
+ return page;
105
+ // Google requires automatic aggregation when a page filter is present. With only a
106
+ // page grouping, preserve page aggregation after removing the grouping for totals.
107
+ let totalAggregation;
108
+ if (!filters?.some((filter) => filter.dimension === 'page')) {
109
+ if (aggregationType === 'byPage' || aggregationType === 'byProperty')
110
+ totalAggregation = aggregationType;
111
+ else if (reportDimensions.includes('page'))
112
+ totalAggregation = 'byPage';
113
+ }
114
+ const totals = await querySearchAnalytics(auth, property, {
115
+ ...request,
116
+ rowLimit: 1,
117
+ aggregationType: totalAggregation,
54
118
  });
55
- return res.data.rows ?? [];
119
+ return { ...page, summary: summarizeRows(totals.rows), totalAggregationType: totals.aggregationType };
56
120
  }
57
121
  /**
58
122
  * Search Analytics rows 요약.
@@ -60,14 +124,26 @@ export async function searchAnalytics(auth, siteUrl, params) {
60
124
  * 노출이 1인 행과 1000인 행을 동등 취급해 실제 평균 순위를 왜곡한다.
61
125
  */
62
126
  export function summarizeRows(rows) {
63
- const totalClicks = rows.reduce((s, r) => s + (r.clicks ?? 0), 0);
64
- const totalImpressions = rows.reduce((s, r) => s + (r.impressions ?? 0), 0);
65
- const weightedPos = rows.reduce((s, r) => s + (r.position ?? 0) * (r.impressions ?? 0), 0);
127
+ let totalClicks = 0;
128
+ let totalImpressions = 0;
129
+ let positionImpressions = 0;
130
+ let weightedPosition = 0;
131
+ for (const row of rows) {
132
+ const impressions = row.impressions ?? 0;
133
+ totalClicks += row.clicks ?? 0;
134
+ totalImpressions += impressions;
135
+ if (row.position != null && row.position > 0) {
136
+ positionImpressions += impressions;
137
+ weightedPosition += row.position * impressions;
138
+ }
139
+ }
66
140
  return {
67
141
  rowCount: rows.length,
68
142
  totalClicks,
69
143
  totalImpressions,
70
144
  avgCtr: totalImpressions > 0 ? Math.round((totalClicks / totalImpressions) * 10000) / 10000 : 0,
71
- avgPosition: totalImpressions > 0 ? Math.round((weightedPos / totalImpressions) * 100) / 100 : 0,
145
+ avgPosition: totalImpressions > 0 && positionImpressions === totalImpressions
146
+ ? Math.round((weightedPosition / totalImpressions) * 100) / 100
147
+ : null,
72
148
  };
73
149
  }
package/dist/helpers.js CHANGED
@@ -4,13 +4,20 @@ import { getServiceAccountClient, getServiceAccountJson } from './auth/playstore
4
4
  import { getAppStoreCredentials } from './appstore/auth.js';
5
5
  export { ensureFreshAccessToken };
6
6
  const REAUTH_CMD = ' npx -y @yoonion/mimi-seed-mcp mimi-seed-auth';
7
- function formatAuthError(p, profile) {
7
+ function formatAuthError(p, profile, scopes = []) {
8
+ // Scope alternatives are ordered by the caller. Recommend the first available domain.
9
+ const domain = scopes.flatMap(domainsForScope)[0];
10
+ const reauthCommand = [
11
+ REAUTH_CMD,
12
+ profile === undefined ? '' : ` --profile ${profile}`,
13
+ domain ? ` --domains ${domain}` : '',
14
+ ].join('');
8
15
  // 재로그인 안내는 needsReauth 인 경우에만 — CONFIG_FETCH_FAILED 처럼 재로그인이
9
16
  // 해법이 아닌 에러에 무조건 붙이면 같은 실패를 반복하게 만든다.
10
17
  return [
11
18
  `❌ [${p.code}] ${p.message}`,
12
19
  p.hint ? `→ ${p.hint}` : '',
13
- ...(p.needsReauth ? ['', '터미널에서 재로그인:', profile === undefined ? REAUTH_CMD : `${REAUTH_CMD} --profile ${profile}`] : []),
20
+ ...(p.needsReauth ? ['', '터미널에서 재로그인:', reauthCommand] : []),
14
21
  ]
15
22
  .filter((l) => l !== '')
16
23
  .join('\n');
@@ -28,23 +35,19 @@ function formatAuthError(p, profile) {
28
35
  *
29
36
  * OAuth 토큰에만 적용된다 — SA JWT 는 자체 scopes 로 토큰을 받으므로 이 검사 대상이 아니다.
30
37
  */
31
- function assertStoredScope(requiredScope, scopeStr, profile) {
32
- if (!requiredScope)
38
+ function assertStoredScope(scopes, scopeStr, profile) {
39
+ if (scopes.length === 0)
33
40
  return;
34
- const scopes = typeof requiredScope === 'string' ? [requiredScope] : requiredScope;
35
41
  const grantedScopes = scopeStr?.split(/\s+/);
36
42
  if (scopes.some((scope) => grantedScopes ? grantedScopes.includes(scope) : isPreTrackingScope(scope)))
37
43
  return;
38
- const domainArg = [...new Set(scopes.flatMap(domainsForScope))].join(',');
39
44
  throw new Error(formatAuthError({
40
45
  code: 'INSUFFICIENT_SCOPE',
41
46
  message: `이 도구는 추가 권한이 필요해 (${scopes.join(' 또는 ')}). 현재 로그인에 그 권한이 없어.`,
42
- hint: domainArg
43
- ? `mimi-seed-auth${profile === undefined ? '' : ` --profile ${profile}`} --domains ${domainArg} 로 재로그인하면 기존 권한은 유지한 채 이 권한만 추가돼.`
44
- : 'mimi-seed-auth 로 재로그인하면 새 권한이 부여돼.',
47
+ hint: '아래 명령으로 로그인하면 기존 권한을 유지하면서 필요한 권한을 추가할 수 있어.',
45
48
  retriable: false,
46
49
  needsReauth: true,
47
- }));
50
+ }, profile, scopes));
48
51
  }
49
52
  /**
50
53
  * OAuth 클라이언트 확보 — 호출 전에 access_token 을 사전 갱신하고,
@@ -56,9 +59,10 @@ function assertStoredScope(requiredScope, scopeStr, profile) {
56
59
  * 스코프 배열을 넘기면 그중 하나만 부여되어 있어도 통과한다.
57
60
  */
58
61
  export async function requireAuth(requiredScope, profile) {
62
+ const scopes = typeof requiredScope === 'string' ? [requiredScope] : requiredScope ?? [];
59
63
  const result = await ensureFreshAccessToken(undefined, profile);
60
64
  if (result.status === 'unauthenticated' || result.status === 'expired_refresh_failed') {
61
- throw new Error(formatAuthError(result.error, profile));
65
+ throw new Error(formatAuthError(result.error, profile, scopes));
62
66
  }
63
67
  const client = getAuthenticatedClient(profile, result.tokens);
64
68
  if (!client) {
@@ -68,10 +72,10 @@ export async function requireAuth(requiredScope, profile) {
68
72
  hint: 'mimi-seed-auth 로 로그인하세요.',
69
73
  retriable: false,
70
74
  needsReauth: true,
71
- }));
75
+ }, profile, scopes));
72
76
  }
73
77
  // 같은 토큰으로 인증 클라이언트를 만든 뒤 해당 토큰의 스코프를 검사한다.
74
- assertStoredScope(requiredScope, result.tokens.scope, profile);
78
+ assertStoredScope(scopes, result.tokens.scope, profile);
75
79
  return client;
76
80
  }
77
81
  export const PLAY_AUTH_HINT = [
@@ -118,7 +122,7 @@ export async function requirePlayStoreAuth(packageName, requiredScope) {
118
122
  throw new Error(PLAY_AUTH_HINT);
119
123
  // OAuth 폴백일 때만 스코프 pre-flight — SA JWT 는 자체 scopes 로 토큰을 받으므로
120
124
  // (getServiceAccountClient 가 reporting 스코프를 이미 싣는다) 해당 없음.
121
- assertStoredScope(requiredScope, result.tokens.scope);
125
+ assertStoredScope(requiredScope ? [requiredScope] : [], result.tokens.scope);
122
126
  return oauth;
123
127
  }
124
128
  export function requireServiceAccountJson(packageName) {
@@ -1,71 +1,72 @@
1
1
  import { z } from 'zod';
2
+ import { GOOGLE_PROFILE_ID } from '../auth/google-auth.js';
3
+ import { GSC_READ_SCOPES, GSC_WRITE_SCOPE } from '../auth/scopes.js';
2
4
  import { requireAuth } from '../helpers.js';
3
5
  import * as gsc from '../gsc/tools.js';
4
6
  import { jsonResult, textResult } from '../lib/mcp-response.js';
5
7
  const SITE_URL_DESC = "Search Console 속성 식별자. 도메인 속성은 'sc-domain:example.com', URL 접두어 속성은 'https://example.com/' 형식.";
8
+ const googleProfile = z.string().regex(GOOGLE_PROFILE_ID).optional().describe('Google 로그인 프로필. 생략하면 기본 계정을 사용.');
6
9
  export function registerGscTools(server) {
7
- server.tool('gsc_list_sites', 'Search Console에 등록된(권한 있는) 속성 목록 + 권한 레벨 조회. siteUrl 값을 확인할 때 먼저 호출.', {}, async () => {
8
- const auth = await requireAuth();
10
+ server.tool('gsc_list_sites', 'Search Console에 등록된(권한 있는) 속성 목록 + 권한 레벨 조회. siteUrl 값을 확인할 때 먼저 호출.', { profile: googleProfile }, async ({ profile }) => {
11
+ const auth = await requireAuth(GSC_READ_SCOPES, profile);
9
12
  const sites = await gsc.listSites(auth);
10
13
  return jsonResult(sites);
11
14
  });
12
- server.tool('gsc_list_sitemaps', '속성에 제출된 사이트맵 목록 (마지막 다운로드 시각, 경고/오류 수, submitted/indexed 카운트). ⚠️ 사이트맵 리포트의 indexed 수치는 신뢰도 낮음 — 실제 색인 여부는 gsc_inspect_url 로 확인.', {
15
+ server.tool('gsc_list_sitemaps', '속성에 제출된 사이트맵 목록 (URL 제출 수, 마지막 다운로드 시각, 경고/오류 수). URL별 색인 상태는 gsc_inspect_url로 조회.', {
13
16
  siteUrl: z.string().describe(SITE_URL_DESC),
14
17
  sitemapIndex: z.string().optional().describe('사이트맵 인덱스 URL — 인덱스 하위 사이트맵만 보고 싶을 때'),
15
- }, async ({ siteUrl, sitemapIndex }) => {
16
- const auth = await requireAuth();
18
+ profile: googleProfile,
19
+ }, async ({ siteUrl, sitemapIndex, profile }) => {
20
+ const auth = await requireAuth(GSC_READ_SCOPES, profile);
17
21
  const sitemaps = await gsc.listSitemaps(auth, siteUrl, sitemapIndex);
18
22
  return jsonResult(sitemaps);
19
23
  });
20
- server.tool('gsc_get_sitemap', '특정 사이트맵 1개의 상세(타입별 submitted/indexed, 경고/오류, 처리 시각) 조회.', {
24
+ server.tool('gsc_get_sitemap', '특정 사이트맵 1개의 상세 조회 (유형별 URL 제출 수, 경고/오류, 처리 시각).', {
21
25
  siteUrl: z.string().describe(SITE_URL_DESC),
22
26
  feedpath: z.string().describe('사이트맵 전체 URL (예: https://example.com/sitemap.xml)'),
23
- }, async ({ siteUrl, feedpath }) => {
24
- const auth = await requireAuth();
27
+ profile: googleProfile,
28
+ }, async ({ siteUrl, feedpath, profile }) => {
29
+ const auth = await requireAuth(GSC_READ_SCOPES, profile);
25
30
  const sitemap = await gsc.getSitemap(auth, siteUrl, feedpath);
26
31
  return jsonResult(sitemap);
27
32
  });
28
- server.tool('gsc_submit_sitemap', '사이트맵을 Search Console에 제출(또는 재제출)해 재크롤을 유도. webmasters read-write 스코프 필요.', {
33
+ server.tool('gsc_submit_sitemap', '사이트맵을 Search Console에 제출하거나 재제출. webmasters 쓰기 권한 필요.', {
29
34
  siteUrl: z.string().describe(SITE_URL_DESC),
30
35
  feedpath: z.string().describe('제출할 사이트맵 전체 URL (예: https://example.com/sitemap.xml)'),
31
- }, async ({ siteUrl, feedpath }) => {
32
- const auth = await requireAuth();
36
+ profile: googleProfile,
37
+ }, async ({ siteUrl, feedpath, profile }) => {
38
+ const auth = await requireAuth(GSC_WRITE_SCOPE, profile);
33
39
  const result = await gsc.submitSitemap(auth, siteUrl, feedpath);
34
- return textResult(`✅ 사이트맵 제출 완료.\n ${result.submitted}\n\n반영까지 수 분~수 시간 걸려. gsc_list_sitemaps 로 lastDownloaded 갱신을 확인해.`);
40
+ return textResult(`✅ 사이트맵 제출 완료.\n ${result.submitted}\n\n처리 상태는 gsc_get_sitemap으로 확인해.`);
35
41
  });
36
- server.tool('gsc_inspect_url', 'URL 1개의 실제 색인 상태 검사 (coverageState, robots.txt 허용 여부, 마지막 크롤 시각, 정규 URL, 리치 결과). 사이트맵 리포트보다 정확한 색인 진단의 단일 출처.', {
42
+ server.tool('gsc_inspect_url', 'Google 색인에 기록된 URL 1개의 상태 조회 (coverageState, robots.txt, 마지막 크롤 시각, 정규 URL, 리치 결과).', {
37
43
  siteUrl: z.string().describe(SITE_URL_DESC),
38
44
  inspectionUrl: z.string().describe("검사할 전체 URL — 반드시 siteUrl 속성 하위여야 함 (예: 'https://example.com/page')"),
39
45
  languageCode: z.string().optional().describe("이슈 메시지 언어 (BCP-47, 예: 'ko', 'en-US'). 기본 en-US"),
40
- }, async ({ siteUrl, inspectionUrl, languageCode }) => {
41
- const auth = await requireAuth();
46
+ profile: googleProfile,
47
+ }, async ({ siteUrl, inspectionUrl, languageCode, profile }) => {
48
+ const auth = await requireAuth(GSC_READ_SCOPES, profile);
42
49
  const result = await gsc.inspectUrl(auth, siteUrl, inspectionUrl, languageCode ?? 'en-US');
43
50
  return jsonResult(result);
44
51
  });
45
- server.tool('gsc_search_analytics', '검색 성과 데이터 조회 (클릭·노출·CTR·평균순위). dimensions로 query/page/country/device/date/searchAppearance 별 분해. 요약(가중 평균순위 포함) + rows 반환.', {
52
+ server.tool('gsc_search_analytics', 'Google 검색 성과 조회. 분해 결과의 rowSummary는 현재 페이지 소계이며 상세 행 일부는 Google에서 생략할 수 있음. 전체 집계는 summary로 반환.', {
46
53
  siteUrl: z.string().describe(SITE_URL_DESC),
47
- startDate: z.string().describe('시작일 (YYYY-MM-DD)'),
48
- endDate: z.string().describe('종료일 (YYYY-MM-DD)'),
49
- dimensions: z.string().optional().describe('쉼표 구분 분해 차원: query,page,country,device,date,searchAppearance (생략 시 전체 합계)'),
50
- rowLimit: z.number().int().min(1).max(25000).optional().describe('최대 행 수 (기본 1000, 최대 25000)'),
51
- type: z.enum(['web', 'image', 'video', 'news', 'discover', 'googleNews']).optional().describe('검색 유형 필터 (기본 web)'),
52
- }, async ({ siteUrl, startDate, endDate, dimensions, rowLimit, type }) => {
53
- const auth = await requireAuth();
54
- const dims = dimensions
55
- ? dimensions.split(',').map((d) => d.trim()).filter(Boolean)
56
- : undefined;
57
- const rows = await gsc.searchAnalytics(auth, siteUrl, {
58
- startDate,
59
- endDate,
60
- dimensions: dims,
61
- rowLimit,
62
- type,
63
- });
64
- return jsonResult({
65
- period: { startDate, endDate },
66
- dimensions: dims ?? [],
67
- summary: gsc.summarizeRows(rows),
68
- rows,
69
- });
54
+ startDate: z.iso.date().describe('시작일 (YYYY-MM-DD, 미국 태평양 시간 기준, 포함)'),
55
+ endDate: z.iso.date().describe('종료일 (YYYY-MM-DD, 미국 태평양 시간 기준, 포함)'),
56
+ dimensions: z.string().optional().describe('쉼표 구분 분해 차원 (예: query,page,country,device,date,searchAppearance). 생략 시 집계.'),
57
+ rowLimit: z.number().int().min(1).max(25000).optional().describe('분해 조회의 페이지당 최대 행 수. 기본 1000.'),
58
+ startRow: z.number().int().nonnegative().optional().describe('분해 조회 시작 위치. 기본 0. 다음 페이지는 pagination.nextStartRow 사용. 클릭 수가 같은 행의 순서는 Google이 보장하지 않음.'),
59
+ type: z.enum(gsc.SEARCH_TYPES).optional().describe('검색 유형 (기본 web)'),
60
+ filters: z.array(z.strictObject({
61
+ dimension: z.enum(gsc.SEARCH_FILTER_DIMENSIONS),
62
+ operator: z.enum(gsc.SEARCH_FILTER_OPERATORS).optional().describe('기본 equals'),
63
+ expression: z.string().min(1).max(4096),
64
+ })).optional().describe('Google에 전달할 필터. 모든 조건이 일치하는 데이터만 집계.'),
65
+ summaryOnly: z.boolean().optional().describe('true면 분해·페이지 옵션을 무시하고 집계만 반환. 필터는 적용.'),
66
+ includeTotals: z.boolean().optional().describe('true면 분해 조회에 같은 기간·필터의 Google 집계를 추가. API 호출 1회 추가.'),
67
+ profile: googleProfile,
68
+ }, async ({ siteUrl, profile, ...params }) => {
69
+ const auth = await requireAuth(GSC_READ_SCOPES, profile);
70
+ return jsonResult(await gsc.searchAnalytics(auth, siteUrl, params));
70
71
  });
71
72
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yoonion/mimi-seed-mcp",
3
- "version": "0.23.4",
3
+ "version": "0.24.0",
4
4
  "description": "Mimi Seed MCP server \u2014 Firebase + AdMob + Google Play + App Store management for Claude Code / Codex / Cursor / any MCP client.",
5
5
  "type": "module",
6
6
  "imports": {