@yoonion/mimi-seed-mcp 0.3.22 → 0.3.24

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.
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { registerAiTools } from './registers/ai.js';
11
11
  import { registerBigqueryTools } from './registers/bigquery.js';
12
12
  import { registerAuthTools } from './registers/auth.js';
13
13
  import { registerCiTools } from './registers/ci.js';
14
+ import { registerInstagramTools } from './registers/instagram.js';
14
15
  import { registerPrompts } from './prompts.js';
15
16
  import { registerResources } from './resources.js';
16
17
  const server = new McpServer({
@@ -27,6 +28,7 @@ registerAiTools(server);
27
28
  registerBigqueryTools(server);
28
29
  registerAuthTools(server);
29
30
  registerCiTools(server);
31
+ registerInstagramTools(server);
30
32
  registerPrompts(server);
31
33
  registerResources(server);
32
34
  // `npx -y @yoonion/mimi-seed-mcp <subcommand>` 처리.
@@ -0,0 +1,19 @@
1
+ import type { InstagramConfig } from './config.js';
2
+ export declare function apiBaseFor(token: string): string;
3
+ export interface InstagramAccount {
4
+ id: string;
5
+ username: string;
6
+ name?: string;
7
+ profile_picture_url?: string;
8
+ account_type?: string;
9
+ followers_count?: number;
10
+ media_count?: number;
11
+ }
12
+ export declare function getAccount(cfg: InstagramConfig): Promise<InstagramAccount>;
13
+ export declare function fetchUserId(accessToken: string): Promise<string>;
14
+ export interface PublishResult {
15
+ id: string;
16
+ permalink?: string;
17
+ }
18
+ export declare function postImage(cfg: InstagramConfig, imageUrl: string, caption: string): Promise<PublishResult>;
19
+ export declare function postCarousel(cfg: InstagramConfig, imageUrls: string[], caption: string): Promise<PublishResult>;
@@ -0,0 +1,108 @@
1
+ // 두 가지 Meta API:
2
+ // IGAA... = Instagram API with Instagram Login (2024 신규) — graph.instagram.com
3
+ // EAA... = Instagram Graph API via Facebook Login — graph.facebook.com
4
+ // 토큰 prefix로 자동 분기. 엔드포인트 path는 둘 다 동일.
5
+ export function apiBaseFor(token) {
6
+ if (token.startsWith('IGAA'))
7
+ return 'https://graph.instagram.com/v21.0';
8
+ return 'https://graph.facebook.com/v21.0';
9
+ }
10
+ async function igFetch(token, endpoint, params, method = 'GET') {
11
+ const url = new URL(`${apiBaseFor(token)}${endpoint}`);
12
+ let body;
13
+ if (method === 'GET') {
14
+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
15
+ }
16
+ else {
17
+ body = new URLSearchParams(params).toString();
18
+ }
19
+ const res = await fetch(url.toString(), {
20
+ method,
21
+ body,
22
+ headers: method === 'POST' ? { 'Content-Type': 'application/x-www-form-urlencoded' } : undefined,
23
+ });
24
+ const text = await res.text();
25
+ if (!res.ok) {
26
+ let msg = text;
27
+ try {
28
+ const parsed = JSON.parse(text);
29
+ if (parsed.error) {
30
+ msg = `${parsed.error.message} (code ${parsed.error.code}${parsed.error.error_subcode ? `/${parsed.error.error_subcode}` : ''})`;
31
+ }
32
+ }
33
+ catch { /* fall through with raw text */ }
34
+ throw new Error(`Instagram API ${res.status}: ${msg}`);
35
+ }
36
+ return JSON.parse(text);
37
+ }
38
+ export async function getAccount(cfg) {
39
+ // graph.instagram.com 은 name/profile_picture_url 필드를 받지 않을 수 있어
40
+ // 두 API 공통으로 안전한 필드만 요청
41
+ const fields = cfg.accessToken.startsWith('IGAA')
42
+ ? 'id,username,account_type,followers_count,media_count'
43
+ : 'id,username,name,profile_picture_url,account_type,followers_count,media_count';
44
+ return igFetch(cfg.accessToken, `/${cfg.userId}`, {
45
+ fields,
46
+ access_token: cfg.accessToken,
47
+ });
48
+ }
49
+ // 토큰만으로 user ID 자동 조회 (양쪽 API 지원)
50
+ export async function fetchUserId(accessToken) {
51
+ if (accessToken.startsWith('IGAA')) {
52
+ // Instagram Login: GET /me?fields=user_id,username
53
+ const res = await igFetch(accessToken, '/me', { fields: 'user_id,username', access_token: accessToken });
54
+ // graph.instagram.com 은 v21.0에서 user_id 또는 id 둘 중 하나 반환
55
+ return res.user_id ?? res.id;
56
+ }
57
+ // Facebook Login: GET /me/accounts → instagram_business_account.id
58
+ const res = await igFetch(accessToken, '/me/accounts', { fields: 'instagram_business_account', access_token: accessToken });
59
+ const id = res.data?.[0]?.instagram_business_account?.id;
60
+ if (!id) {
61
+ throw new Error('Facebook Page에 연결된 Instagram Business Account를 찾지 못했습니다.\n' +
62
+ 'Facebook Page → Settings → Linked Accounts에서 IG 계정을 연결하세요.');
63
+ }
64
+ return id;
65
+ }
66
+ async function fetchPermalink(cfg, mediaId) {
67
+ try {
68
+ const meta = await igFetch(cfg.accessToken, `/${mediaId}`, { fields: 'permalink', access_token: cfg.accessToken });
69
+ return meta.permalink;
70
+ }
71
+ catch {
72
+ return undefined;
73
+ }
74
+ }
75
+ export async function postImage(cfg, imageUrl, caption) {
76
+ // Step 1: image container 생성
77
+ const container = await igFetch(cfg.accessToken, `/${cfg.userId}/media`, { image_url: imageUrl, caption, access_token: cfg.accessToken }, 'POST');
78
+ // Step 2: publish
79
+ const published = await igFetch(cfg.accessToken, `/${cfg.userId}/media_publish`, { creation_id: container.id, access_token: cfg.accessToken }, 'POST');
80
+ return {
81
+ id: published.id,
82
+ permalink: await fetchPermalink(cfg, published.id),
83
+ };
84
+ }
85
+ export async function postCarousel(cfg, imageUrls, caption) {
86
+ if (imageUrls.length < 2 || imageUrls.length > 10) {
87
+ throw new Error(`캐러셀은 2~10장의 이미지가 필요합니다 (받은 수: ${imageUrls.length}).`);
88
+ }
89
+ // Step 1: 각 이미지를 children container로 생성 (sequential — 일부 실패 시 부분 결과 명확)
90
+ const childIds = [];
91
+ for (const url of imageUrls) {
92
+ const child = await igFetch(cfg.accessToken, `/${cfg.userId}/media`, { image_url: url, is_carousel_item: 'true', access_token: cfg.accessToken }, 'POST');
93
+ childIds.push(child.id);
94
+ }
95
+ // Step 2: carousel container 생성
96
+ const carousel = await igFetch(cfg.accessToken, `/${cfg.userId}/media`, {
97
+ media_type: 'CAROUSEL',
98
+ children: childIds.join(','),
99
+ caption,
100
+ access_token: cfg.accessToken,
101
+ }, 'POST');
102
+ // Step 3: publish
103
+ const published = await igFetch(cfg.accessToken, `/${cfg.userId}/media_publish`, { creation_id: carousel.id, access_token: cfg.accessToken }, 'POST');
104
+ return {
105
+ id: published.id,
106
+ permalink: await fetchPermalink(cfg, published.id),
107
+ };
108
+ }
@@ -0,0 +1,9 @@
1
+ export interface InstagramConfig {
2
+ accessToken: string;
3
+ userId: string;
4
+ expiresAt?: string;
5
+ username?: string;
6
+ }
7
+ export declare function loadInstagramConfig(): InstagramConfig | null;
8
+ export declare function saveInstagramConfig(cfg: InstagramConfig): void;
9
+ export declare function requireInstagramConfig(): InstagramConfig;
@@ -0,0 +1,31 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ const CONFIG_PATH = path.join(os.homedir(), '.mimi-seed', 'instagram.json');
5
+ export function loadInstagramConfig() {
6
+ try {
7
+ return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ }
13
+ export function saveInstagramConfig(cfg) {
14
+ const dir = path.dirname(CONFIG_PATH);
15
+ if (!fs.existsSync(dir)) {
16
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
17
+ }
18
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2));
19
+ if (process.platform !== 'win32') {
20
+ fs.chmodSync(CONFIG_PATH, 0o600);
21
+ }
22
+ }
23
+ export function requireInstagramConfig() {
24
+ const cfg = loadInstagramConfig();
25
+ if (!cfg) {
26
+ throw new Error('Instagram 설정이 없습니다.\n' +
27
+ 'instagram_save_config 도구로 먼저 설정해주세요.\n' +
28
+ '예: instagram_save_config(accessToken="...", userId="...")');
29
+ }
30
+ return cfg;
31
+ }
@@ -0,0 +1,2 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function registerInstagramTools(server: McpServer): void;
@@ -0,0 +1,152 @@
1
+ import { z } from 'zod';
2
+ import { requireInstagramConfig, saveInstagramConfig } from '../instagram/config.js';
3
+ import * as api from '../instagram/api.js';
4
+ export function registerInstagramTools(server) {
5
+ server.tool('instagram_save_config', [
6
+ 'Instagram 토큰을 ~/.mimi-seed/instagram.json (mode 0600)에 저장합니다.',
7
+ 'accessToken은 두 형식 모두 자동 감지:',
8
+ ' IGAA... = Instagram API with Instagram Login (Meta 신규, FB Page 불필요)',
9
+ ' EAA... = Instagram Graph API via Facebook Login (FB Page+IG Business 연결 필요)',
10
+ 'userId 미입력 시 토큰으로 자동 조회 (/me 또는 /me/accounts).',
11
+ '저장 직후 토큰 유효성도 자동 검증.',
12
+ ].join(' '), {
13
+ accessToken: z.string().describe('Long-lived access token (60일)'),
14
+ userId: z.string().optional().describe('Instagram Business Account ID (생략 시 자동 조회)'),
15
+ assumeIssuedNow: z.boolean().default(true).describe('expiresAt = 지금 + 60일 자동 계산'),
16
+ }, async ({ accessToken, userId, assumeIssuedNow }) => {
17
+ const apiType = accessToken.startsWith('IGAA') ? 'Instagram Login' : 'Facebook Login';
18
+ // userId 자동 조회
19
+ let resolvedUserId = userId;
20
+ if (!resolvedUserId) {
21
+ try {
22
+ resolvedUserId = await api.fetchUserId(accessToken);
23
+ }
24
+ catch (err) {
25
+ return {
26
+ content: [{
27
+ type: 'text',
28
+ text: [
29
+ `❌ userId 자동 조회 실패 (${apiType})`,
30
+ ` ${err.message}`,
31
+ ``,
32
+ `userId를 명시적으로 전달하거나 토큰을 다시 확인하세요.`,
33
+ ].join('\n'),
34
+ }],
35
+ };
36
+ }
37
+ }
38
+ const expiresAt = assumeIssuedNow
39
+ ? new Date(Date.now() + 60 * 24 * 60 * 60 * 1000).toISOString()
40
+ : undefined;
41
+ // 검증 — 잘못된 토큰이면 즉시 알림
42
+ try {
43
+ const account = await api.getAccount({ accessToken, userId: resolvedUserId });
44
+ // 검증 성공 → 최종 저장
45
+ saveInstagramConfig({
46
+ accessToken,
47
+ userId: resolvedUserId,
48
+ expiresAt,
49
+ username: account.username,
50
+ });
51
+ return {
52
+ content: [{
53
+ type: 'text',
54
+ text: [
55
+ `✅ Instagram 연결 확인 완료 (${apiType})`,
56
+ ` 계정: @${account.username}${account.name ? ` (${account.name})` : ''}`,
57
+ ` ID: ${account.id}`,
58
+ account.account_type ? ` 타입: ${account.account_type}` : '',
59
+ account.followers_count !== undefined ? ` 팔로워: ${account.followers_count.toLocaleString()}` : '',
60
+ account.media_count !== undefined ? ` 게시물: ${account.media_count}` : '',
61
+ expiresAt ? ` 토큰 만료(추정): ${expiresAt.slice(0, 10)}` : '',
62
+ ].filter(Boolean).join('\n'),
63
+ }],
64
+ };
65
+ }
66
+ catch (err) {
67
+ // 검증 실패 — 저장은 하지 않고 사용자에게 알림
68
+ return {
69
+ content: [{
70
+ type: 'text',
71
+ text: [
72
+ `❌ 토큰 검증 실패 (${apiType})`,
73
+ ` userId: ${resolvedUserId}`,
74
+ ` ${err.message}`,
75
+ ``,
76
+ `토큰을 다시 발급받거나 userId를 직접 지정해보세요.`,
77
+ ].join('\n'),
78
+ }],
79
+ };
80
+ }
81
+ });
82
+ server.tool('instagram_get_account', 'Instagram 계정 정보 조회 + 저장된 토큰 유효성 검증.', {}, async () => {
83
+ const cfg = requireInstagramConfig();
84
+ const account = await api.getAccount(cfg);
85
+ const remainingDays = cfg.expiresAt
86
+ ? Math.round((new Date(cfg.expiresAt).getTime() - Date.now()) / (24 * 60 * 60 * 1000))
87
+ : null;
88
+ return {
89
+ content: [{
90
+ type: 'text',
91
+ text: [
92
+ `@${account.username}${account.name ? ` (${account.name})` : ''}`,
93
+ ` ID: ${account.id}`,
94
+ account.account_type ? ` 타입: ${account.account_type}` : '',
95
+ account.followers_count !== undefined ? ` 팔로워: ${account.followers_count.toLocaleString()}` : '',
96
+ account.media_count !== undefined ? ` 게시물: ${account.media_count}` : '',
97
+ remainingDays !== null
98
+ ? remainingDays > 7
99
+ ? ` 토큰: ${remainingDays}일 남음`
100
+ : remainingDays > 0
101
+ ? ` ⚠️ 토큰 ${remainingDays}일 남음 — 곧 갱신 필요`
102
+ : ` ❌ 토큰 만료됨 — instagram_save_config로 재저장`
103
+ : '',
104
+ ].filter(Boolean).join('\n'),
105
+ }],
106
+ };
107
+ });
108
+ server.tool('instagram_post_image', [
109
+ '단일 이미지를 Instagram에 게시합니다.',
110
+ 'imageUrl은 public URL이어야 합니다 (Graph API 제약). 로컬 파일은 미리 S3/R2/Cloudinary 등에 업로드 필요.',
111
+ '캡션에는 해시태그(#)와 멘션(@) 포함 가능. 줄바꿈 \\n 사용.',
112
+ '2-step API: container 생성 → media_publish.',
113
+ ].join(' '), {
114
+ imageUrl: z.string().url().describe('이미지의 public URL (HTTPS 권장)'),
115
+ caption: z.string().describe('캡션 — 해시태그/멘션/줄바꿈 포함 가능'),
116
+ }, async ({ imageUrl, caption }) => {
117
+ const cfg = requireInstagramConfig();
118
+ const result = await api.postImage(cfg, imageUrl, caption);
119
+ return {
120
+ content: [{
121
+ type: 'text',
122
+ text: [
123
+ `✅ 게시 완료`,
124
+ ` media_id: ${result.id}`,
125
+ result.permalink ? ` URL: ${result.permalink}` : '',
126
+ ].filter(Boolean).join('\n'),
127
+ }],
128
+ };
129
+ });
130
+ server.tool('instagram_post_carousel', [
131
+ '여러 이미지를 캐러셀(swipe)로 게시합니다. 2~10장.',
132
+ '모든 이미지는 public URL이어야 함.',
133
+ '3-step API: 각 이미지 children container → carousel container → publish.',
134
+ '일부 이미지에서 실패하면 전체 실패 (이미 만든 children container는 자동 삭제 안 됨 — Instagram이 알아서 처리).',
135
+ ].join(' '), {
136
+ imageUrls: z.array(z.string().url()).min(2).max(10).describe('이미지 URL 배열 (2~10장)'),
137
+ caption: z.string().describe('캡션'),
138
+ }, async ({ imageUrls, caption }) => {
139
+ const cfg = requireInstagramConfig();
140
+ const result = await api.postCarousel(cfg, imageUrls, caption);
141
+ return {
142
+ content: [{
143
+ type: 'text',
144
+ text: [
145
+ `✅ 캐러셀 ${imageUrls.length}장 게시 완료`,
146
+ ` media_id: ${result.id}`,
147
+ result.permalink ? ` URL: ${result.permalink}` : '',
148
+ ].filter(Boolean).join('\n'),
149
+ }],
150
+ };
151
+ });
152
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yoonion/mimi-seed-mcp",
3
- "version": "0.3.22",
3
+ "version": "0.3.24",
4
4
  "description": "Mimi Seed MCP server — Firebase + AdMob + Google Play + App Store management for Claude Code / Cursor / any MCP client.",
5
5
  "type": "module",
6
6
  "bin": {