@channel47/meta-ads-mcp 1.0.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.
- package/LICENSE +21 -0
- package/README.md +137 -0
- package/package.json +48 -0
- package/server/auth.js +40 -0
- package/server/http.js +186 -0
- package/server/index.js +208 -0
- package/server/prompts/templates.js +112 -0
- package/server/resources/entity-fields-reference.md +134 -0
- package/server/resources/graph-api-reference.md +78 -0
- package/server/resources/index.js +65 -0
- package/server/resources/rate-limits-and-quotas.md +33 -0
- package/server/tools/list-accounts.js +63 -0
- package/server/tools/mutate.js +179 -0
- package/server/tools/query.js +157 -0
- package/server/utils/errors.js +12 -0
- package/server/utils/field-defaults.js +164 -0
- package/server/utils/mutate-operations.js +149 -0
- package/server/utils/paginate.js +30 -0
- package/server/utils/response-format.js +63 -0
- package/server/utils/validation.js +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 channel47
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# @channel47/meta-ads-mcp
|
|
2
|
+
|
|
3
|
+
MCP server for Meta Ads (Facebook + Instagram) using the Graph API (`v25.0`).
|
|
4
|
+
|
|
5
|
+
This server exposes three tools expected by channel47 Meta workflows:
|
|
6
|
+
|
|
7
|
+
- `list_accounts`
|
|
8
|
+
- `query`
|
|
9
|
+
- `mutate`
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
### Standalone
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npx @channel47/meta-ads-mcp@latest
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
### Monorepo Development
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
cd mcps
|
|
23
|
+
npm install
|
|
24
|
+
npm run test
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Configuration
|
|
28
|
+
|
|
29
|
+
### Required
|
|
30
|
+
|
|
31
|
+
| Variable | Description |
|
|
32
|
+
|----------|-------------|
|
|
33
|
+
| `META_ADS_ACCESS_TOKEN` | Meta Graph API access token (long-lived user token or system user token) |
|
|
34
|
+
|
|
35
|
+
### Optional
|
|
36
|
+
|
|
37
|
+
| Variable | Description |
|
|
38
|
+
|----------|-------------|
|
|
39
|
+
| `META_ADS_ACCOUNT_ID` | Default ad account ID used when `account_id` is omitted |
|
|
40
|
+
| `META_ADS_READ_ONLY` | Set to `true` to disable live mutations |
|
|
41
|
+
| `META_ADS_REQUEST_TIMEOUT_MS` | HTTP request timeout in milliseconds (default `30000`) |
|
|
42
|
+
|
|
43
|
+
## Tool Reference
|
|
44
|
+
|
|
45
|
+
### `list_accounts`
|
|
46
|
+
|
|
47
|
+
List accessible ad accounts from `GET /me/adaccounts`.
|
|
48
|
+
|
|
49
|
+
**Params:**
|
|
50
|
+
- `status` (optional): status filter (`ACTIVE`, `DISABLED`, etc.)
|
|
51
|
+
|
|
52
|
+
**Notes:**
|
|
53
|
+
- Account IDs are normalized without `act_` prefix
|
|
54
|
+
- Includes raw `account_status` and mapped status text
|
|
55
|
+
- Follows Graph API cursor pagination to return all accessible accounts
|
|
56
|
+
|
|
57
|
+
### `query`
|
|
58
|
+
|
|
59
|
+
Structured query wrapper for Meta Graph API entities:
|
|
60
|
+
|
|
61
|
+
- `campaigns`
|
|
62
|
+
- `adsets`
|
|
63
|
+
- `ads`
|
|
64
|
+
- `insights`
|
|
65
|
+
- `audiences`
|
|
66
|
+
- `creatives`
|
|
67
|
+
|
|
68
|
+
**Core params:**
|
|
69
|
+
- `entity` (required)
|
|
70
|
+
- `account_id` (optional if `META_ADS_ACCOUNT_ID` exists)
|
|
71
|
+
- `fields`, `filters`, `sort`, `limit`
|
|
72
|
+
- `inline_insights_fields` (optional on non-`insights` entities): appends nested inline projection like `insights{spend,ctr,frequency}`
|
|
73
|
+
|
|
74
|
+
**Insights params:**
|
|
75
|
+
- `date_range`: preset (`today`, `yesterday`, `last_7d`, `last_14d`, `last_30d`, `this_month`, `this_week_mon_today`, `last_quarter`) or `{ since, until }`
|
|
76
|
+
- `level`: `campaign`, `adset`, or `ad`
|
|
77
|
+
- `time_increment`: `1`, `7`, `monthly`, etc.
|
|
78
|
+
- `breakdowns`: array of dimensions (`age`, `gender`, `publisher_platform`, etc.)
|
|
79
|
+
|
|
80
|
+
### `mutate`
|
|
81
|
+
|
|
82
|
+
Mutation tool with dry-run safety by default.
|
|
83
|
+
|
|
84
|
+
**Operation format:**
|
|
85
|
+
|
|
86
|
+
```json
|
|
87
|
+
{
|
|
88
|
+
"entity": "campaign",
|
|
89
|
+
"action": "update",
|
|
90
|
+
"id": "123456789",
|
|
91
|
+
"params": {
|
|
92
|
+
"daily_budget": "5000"
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Supported entities:**
|
|
98
|
+
- `campaign`
|
|
99
|
+
- `adset`
|
|
100
|
+
- `ad`
|
|
101
|
+
- `audience`
|
|
102
|
+
- `creative`
|
|
103
|
+
|
|
104
|
+
**Supported actions:**
|
|
105
|
+
- `create`
|
|
106
|
+
- `update`
|
|
107
|
+
- `pause`
|
|
108
|
+
- `enable`
|
|
109
|
+
- `archive`
|
|
110
|
+
- `delete`
|
|
111
|
+
|
|
112
|
+
**Top-level params:**
|
|
113
|
+
- `operations` (required)
|
|
114
|
+
- `dry_run` (default `true`)
|
|
115
|
+
- `partial_failure` (default `true`)
|
|
116
|
+
|
|
117
|
+
## Behavior Notes
|
|
118
|
+
|
|
119
|
+
- Auth is sent via `Authorization: Bearer <token>` request header
|
|
120
|
+
- API retries once on:
|
|
121
|
+
- HTTP `429`
|
|
122
|
+
- Graph error codes `17` and `32`
|
|
123
|
+
- For throttled retries, `Retry-After` header is used when available; otherwise fallback is `60s`
|
|
124
|
+
- Requests are aborted on timeout (default `30000ms`, configurable via `META_ADS_REQUEST_TIMEOUT_MS`)
|
|
125
|
+
- Budgets are returned in minor currency units (example: `5000` means `$50.00` USD)
|
|
126
|
+
|
|
127
|
+
## Development Commands
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
cd meta-ads
|
|
131
|
+
npm test
|
|
132
|
+
node server/index.js
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@channel47/meta-ads-mcp",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Meta Ads MCP Server - Query and mutate Meta/Facebook/Instagram ads data via Graph API",
|
|
5
|
+
"main": "server/index.js",
|
|
6
|
+
"bin": {
|
|
7
|
+
"meta-ads-mcp": "server/index.js"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"files": [
|
|
11
|
+
"server/**/*.js",
|
|
12
|
+
"server/**/*.md",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"start": "node server/index.js",
|
|
18
|
+
"test": "node --test *.test.js test/*.test.js",
|
|
19
|
+
"prepublishOnly": "npm test"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"mcp",
|
|
23
|
+
"model-context-protocol",
|
|
24
|
+
"meta-ads",
|
|
25
|
+
"facebook-ads",
|
|
26
|
+
"instagram-ads",
|
|
27
|
+
"analytics",
|
|
28
|
+
"advertising",
|
|
29
|
+
"claude"
|
|
30
|
+
],
|
|
31
|
+
"author": "channel47",
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/channel47/mcps.git",
|
|
36
|
+
"directory": "meta-ads"
|
|
37
|
+
},
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/channel47/mcps/issues"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://github.com/channel47/mcps/tree/main/meta-ads#readme",
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@modelcontextprotocol/sdk": "^1.29.0"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=18.0.0"
|
|
47
|
+
}
|
|
48
|
+
}
|
package/server/auth.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const REQUIRED_ENV_VARS = ['META_ADS_ACCESS_TOKEN'];
|
|
2
|
+
|
|
3
|
+
let cachedAccessToken = null;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Validate required environment variables for Meta Ads auth.
|
|
7
|
+
* @returns {{ valid: boolean, missing: string[] }}
|
|
8
|
+
*/
|
|
9
|
+
export function validateEnvironment() {
|
|
10
|
+
const missing = REQUIRED_ENV_VARS.filter((name) => !process.env[name]);
|
|
11
|
+
return {
|
|
12
|
+
valid: missing.length === 0,
|
|
13
|
+
missing
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Return the configured Meta Ads access token with process-level caching.
|
|
19
|
+
* @returns {Promise<string>}
|
|
20
|
+
*/
|
|
21
|
+
export async function getAccessToken() {
|
|
22
|
+
if (cachedAccessToken) {
|
|
23
|
+
return cachedAccessToken;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const { valid, missing } = validateEnvironment();
|
|
27
|
+
if (!valid) {
|
|
28
|
+
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
cachedAccessToken = String(process.env.META_ADS_ACCESS_TOKEN);
|
|
32
|
+
return cachedAccessToken;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Clear the in-memory token cache (used by tests and local dev flows).
|
|
37
|
+
*/
|
|
38
|
+
export function clearAuthCache() {
|
|
39
|
+
cachedAccessToken = null;
|
|
40
|
+
}
|
package/server/http.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { getAccessToken } from './auth.js';
|
|
2
|
+
import { invalidParamsError } from './utils/errors.js';
|
|
3
|
+
|
|
4
|
+
const META_BASE_URL = 'https://graph.facebook.com/v25.0';
|
|
5
|
+
const RATE_LIMIT_ERROR_CODES = new Set([17, 32]);
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
7
|
+
const DEFAULT_RATE_LIMIT_SLEEP_MS = 60_000;
|
|
8
|
+
|
|
9
|
+
function sleep(ms) {
|
|
10
|
+
return new Promise((resolve) => {
|
|
11
|
+
setTimeout(resolve, ms);
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function normalizePath(path) {
|
|
16
|
+
if (!path) {
|
|
17
|
+
throw new Error('API path is required');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
return path.startsWith('/') ? path : `/${path}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function buildUrl(path, params = {}) {
|
|
24
|
+
const url = new URL(`${META_BASE_URL}${normalizePath(path)}`);
|
|
25
|
+
|
|
26
|
+
for (const [key, value] of Object.entries(params)) {
|
|
27
|
+
if (value === undefined || value === null || value === '') {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
url.searchParams.set(key, String(value));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return url;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function parseResponse(response) {
|
|
37
|
+
const contentType = response.headers.get('content-type') || '';
|
|
38
|
+
|
|
39
|
+
if (contentType.includes('application/json')) {
|
|
40
|
+
return response.json();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const text = await response.text();
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(text);
|
|
46
|
+
} catch {
|
|
47
|
+
return text;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function extractErrorCode(payload) {
|
|
52
|
+
return Number(payload?.error?.code || 0);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function extractErrorMessage(payload) {
|
|
56
|
+
if (payload?.error?.message) {
|
|
57
|
+
return payload.error.message;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (payload?.message) {
|
|
61
|
+
return payload.message;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (typeof payload === 'string' && payload) {
|
|
65
|
+
return payload;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return 'Unknown Meta Ads API error';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function resolveTimeoutMs(timeoutMs) {
|
|
72
|
+
const candidate = timeoutMs ?? process.env.META_ADS_REQUEST_TIMEOUT_MS ?? DEFAULT_TIMEOUT_MS;
|
|
73
|
+
const parsed = Number(candidate);
|
|
74
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
75
|
+
return DEFAULT_TIMEOUT_MS;
|
|
76
|
+
}
|
|
77
|
+
return Math.floor(parsed);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function getRateLimitSleepMs(response) {
|
|
81
|
+
const retryAfter = response?.headers?.get('retry-after');
|
|
82
|
+
if (!retryAfter) {
|
|
83
|
+
return DEFAULT_RATE_LIMIT_SLEEP_MS;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const seconds = Number(retryAfter);
|
|
87
|
+
if (Number.isFinite(seconds) && seconds > 0) {
|
|
88
|
+
return Math.floor(seconds * 1000);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const retryAtMs = Date.parse(retryAfter);
|
|
92
|
+
if (Number.isFinite(retryAtMs)) {
|
|
93
|
+
const delta = retryAtMs - Date.now();
|
|
94
|
+
if (delta > 0) {
|
|
95
|
+
return Math.floor(delta);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return DEFAULT_RATE_LIMIT_SLEEP_MS;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Execute an authenticated Meta Graph API request with timeout and retry handling.
|
|
104
|
+
* @param {string} path
|
|
105
|
+
* @param {Record<string, unknown>} [params]
|
|
106
|
+
* @param {{
|
|
107
|
+
* method?: string,
|
|
108
|
+
* body?: unknown,
|
|
109
|
+
* timeoutMs?: number,
|
|
110
|
+
* retryThrottled?: boolean,
|
|
111
|
+
* sleep?: (ms: number) => Promise<void>
|
|
112
|
+
* }} [options]
|
|
113
|
+
* @returns {Promise<unknown>}
|
|
114
|
+
*/
|
|
115
|
+
export async function metaRequest(
|
|
116
|
+
path,
|
|
117
|
+
params = {},
|
|
118
|
+
{
|
|
119
|
+
method = 'GET',
|
|
120
|
+
body,
|
|
121
|
+
timeoutMs,
|
|
122
|
+
retryThrottled = true,
|
|
123
|
+
sleep: sleepFn = sleep
|
|
124
|
+
} = {}
|
|
125
|
+
) {
|
|
126
|
+
const token = await getAccessToken();
|
|
127
|
+
const url = buildUrl(path, params);
|
|
128
|
+
const resolvedTimeoutMs = resolveTimeoutMs(timeoutMs);
|
|
129
|
+
const controller = new AbortController();
|
|
130
|
+
const timeoutId = setTimeout(() => {
|
|
131
|
+
controller.abort();
|
|
132
|
+
}, resolvedTimeoutMs);
|
|
133
|
+
|
|
134
|
+
const requestOptions = {
|
|
135
|
+
method,
|
|
136
|
+
headers: {
|
|
137
|
+
'Content-Type': 'application/json',
|
|
138
|
+
Authorization: `Bearer ${token}`
|
|
139
|
+
},
|
|
140
|
+
signal: controller.signal
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
if (body !== undefined && body !== null) {
|
|
144
|
+
requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
let response;
|
|
148
|
+
try {
|
|
149
|
+
response = await fetch(url, requestOptions);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (error?.name === 'AbortError') {
|
|
152
|
+
throw new Error(`Meta Ads API request timed out after ${resolvedTimeoutMs}ms`);
|
|
153
|
+
}
|
|
154
|
+
throw error;
|
|
155
|
+
} finally {
|
|
156
|
+
clearTimeout(timeoutId);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const payload = await parseResponse(response);
|
|
160
|
+
|
|
161
|
+
if (response.ok) {
|
|
162
|
+
return payload;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (response.status === 401) {
|
|
166
|
+
const message = extractErrorMessage(payload);
|
|
167
|
+
throw invalidParamsError(`Meta Ads API request failed (${response.status}): ${message}`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const errorCode = extractErrorCode(payload);
|
|
171
|
+
const isRateLimited = response.status === 429 || RATE_LIMIT_ERROR_CODES.has(errorCode);
|
|
172
|
+
if (isRateLimited && retryThrottled) {
|
|
173
|
+
await sleepFn(getRateLimitSleepMs(response));
|
|
174
|
+
|
|
175
|
+
return metaRequest(path, params, {
|
|
176
|
+
method,
|
|
177
|
+
body,
|
|
178
|
+
timeoutMs: resolvedTimeoutMs,
|
|
179
|
+
retryThrottled: false,
|
|
180
|
+
sleep: sleepFn
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const message = extractErrorMessage(payload);
|
|
185
|
+
throw new Error(`Meta Ads API request failed (${response.status}): ${message}`);
|
|
186
|
+
}
|
package/server/index.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
|
+
import {
|
|
5
|
+
CallToolRequestSchema,
|
|
6
|
+
GetPromptRequestSchema,
|
|
7
|
+
ListPromptsRequestSchema,
|
|
8
|
+
ListResourcesRequestSchema,
|
|
9
|
+
ListToolsRequestSchema,
|
|
10
|
+
ReadResourceRequestSchema
|
|
11
|
+
} from '@modelcontextprotocol/sdk/types.js';
|
|
12
|
+
|
|
13
|
+
import { validateEnvironment } from './auth.js';
|
|
14
|
+
import { listAccounts } from './tools/list-accounts.js';
|
|
15
|
+
import { query } from './tools/query.js';
|
|
16
|
+
import { mutate } from './tools/mutate.js';
|
|
17
|
+
import { getPromptsList, renderPrompt } from './prompts/templates.js';
|
|
18
|
+
import { getResourcesList, readResource } from './resources/index.js';
|
|
19
|
+
|
|
20
|
+
const SERVER_NAME = 'meta-ads-mcp';
|
|
21
|
+
const SERVER_VERSION = '1.0.0';
|
|
22
|
+
const READ_ONLY = process.env.META_ADS_READ_ONLY === 'true';
|
|
23
|
+
|
|
24
|
+
const ALL_TOOLS = [
|
|
25
|
+
{
|
|
26
|
+
name: 'list_accounts',
|
|
27
|
+
description: 'List all accessible Meta ad accounts for the authenticated token.',
|
|
28
|
+
inputSchema: {
|
|
29
|
+
type: 'object',
|
|
30
|
+
properties: {
|
|
31
|
+
status: {
|
|
32
|
+
type: 'string',
|
|
33
|
+
description: 'Optional account status filter (e.g. ACTIVE, DISABLED)'
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
name: 'query',
|
|
40
|
+
description: 'Query campaigns, adsets, ads, insights, audiences, or creatives from Meta Graph API, including optional inline nested insights on non-insights entities.',
|
|
41
|
+
inputSchema: {
|
|
42
|
+
type: 'object',
|
|
43
|
+
properties: {
|
|
44
|
+
account_id: {
|
|
45
|
+
type: 'string',
|
|
46
|
+
description: 'Meta account ID. Supports either 123... or act_123...'
|
|
47
|
+
},
|
|
48
|
+
entity: {
|
|
49
|
+
type: 'string',
|
|
50
|
+
enum: ['campaigns', 'adsets', 'ads', 'insights', 'audiences', 'creatives'],
|
|
51
|
+
description: 'Entity type to query'
|
|
52
|
+
},
|
|
53
|
+
fields: {
|
|
54
|
+
anyOf: [
|
|
55
|
+
{ type: 'string' },
|
|
56
|
+
{
|
|
57
|
+
type: 'array',
|
|
58
|
+
items: { type: 'string' }
|
|
59
|
+
}
|
|
60
|
+
],
|
|
61
|
+
description: 'Optional fields selection. Defaults to entity-specific presets.'
|
|
62
|
+
},
|
|
63
|
+
inline_insights_fields: {
|
|
64
|
+
anyOf: [
|
|
65
|
+
{ type: 'string' },
|
|
66
|
+
{
|
|
67
|
+
type: 'array',
|
|
68
|
+
items: { type: 'string' }
|
|
69
|
+
}
|
|
70
|
+
],
|
|
71
|
+
description: 'For non-insights entities, append nested insights projection fields (e.g. spend,ctr,frequency)'
|
|
72
|
+
},
|
|
73
|
+
filters: {
|
|
74
|
+
type: 'array',
|
|
75
|
+
items: { type: 'object' },
|
|
76
|
+
description: 'Optional structured Graph filtering clauses'
|
|
77
|
+
},
|
|
78
|
+
date_range: {
|
|
79
|
+
anyOf: [{ type: 'string' }, { type: 'object' }],
|
|
80
|
+
description: 'Insights-only date range preset or { since, until } object'
|
|
81
|
+
},
|
|
82
|
+
level: {
|
|
83
|
+
type: 'string',
|
|
84
|
+
description: 'Insights-only breakdown level (campaign, adset, ad)'
|
|
85
|
+
},
|
|
86
|
+
time_increment: {
|
|
87
|
+
anyOf: [{ type: 'string' }, { type: 'integer' }],
|
|
88
|
+
description: 'Insights-only increment (1, 7, monthly, etc.)'
|
|
89
|
+
},
|
|
90
|
+
breakdowns: {
|
|
91
|
+
type: 'array',
|
|
92
|
+
items: { type: 'string' },
|
|
93
|
+
description: 'Insights-only dimension breakdowns (e.g. age, gender, publisher_platform)'
|
|
94
|
+
},
|
|
95
|
+
limit: {
|
|
96
|
+
type: 'integer',
|
|
97
|
+
minimum: 1,
|
|
98
|
+
maximum: 1000,
|
|
99
|
+
description: 'Maximum rows to return (default: 100, max: 1000)'
|
|
100
|
+
},
|
|
101
|
+
sort: {
|
|
102
|
+
type: 'string',
|
|
103
|
+
description: 'Optional sort expression'
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
required: ['entity']
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
name: 'mutate',
|
|
111
|
+
description: 'Execute create/update/pause/enable/archive/delete operations for campaign, adset, ad, audience, and creative entities. dry_run defaults to true and performs server-side validation via Meta validate_only API. Creates default to PAUSED status for safety (pass explicit status to override). DELETE is permanent and unrecoverable — prefer pause or archive. Campaign creates require special_ad_categories (use [] if none apply).',
|
|
112
|
+
inputSchema: {
|
|
113
|
+
type: 'object',
|
|
114
|
+
properties: {
|
|
115
|
+
account_id: {
|
|
116
|
+
type: 'string',
|
|
117
|
+
description: 'Meta account ID. Supports either 123... or act_123...'
|
|
118
|
+
},
|
|
119
|
+
operations: {
|
|
120
|
+
type: 'array',
|
|
121
|
+
description: 'Array of operation objects: { entity, action, id?, params? }',
|
|
122
|
+
items: {
|
|
123
|
+
type: 'object'
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
dry_run: {
|
|
127
|
+
type: 'boolean',
|
|
128
|
+
description: 'Validate and preview only (default: true)',
|
|
129
|
+
default: true
|
|
130
|
+
},
|
|
131
|
+
partial_failure: {
|
|
132
|
+
type: 'boolean',
|
|
133
|
+
description: 'Continue executing later operations when one fails (default: true)',
|
|
134
|
+
default: true
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
required: ['operations']
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
];
|
|
141
|
+
|
|
142
|
+
const TOOLS = READ_ONLY ? ALL_TOOLS.filter((tool) => tool.name !== 'mutate') : ALL_TOOLS;
|
|
143
|
+
|
|
144
|
+
const envStatus = validateEnvironment();
|
|
145
|
+
if (!envStatus.valid) {
|
|
146
|
+
console.error(`Missing required environment variables: ${envStatus.missing.join(', ')}`);
|
|
147
|
+
process.exit(1);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (READ_ONLY) {
|
|
151
|
+
console.error('Read-only mode enabled — mutate tool disabled');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const server = new Server(
|
|
155
|
+
{
|
|
156
|
+
name: SERVER_NAME,
|
|
157
|
+
version: SERVER_VERSION
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
capabilities: {
|
|
161
|
+
tools: {},
|
|
162
|
+
prompts: {},
|
|
163
|
+
resources: {}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
169
|
+
|
|
170
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
171
|
+
const { name, arguments: params } = request.params;
|
|
172
|
+
|
|
173
|
+
if (name === 'list_accounts') {
|
|
174
|
+
return listAccounts(params);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (name === 'query') {
|
|
178
|
+
return query(params);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (name === 'mutate') {
|
|
182
|
+
if (READ_ONLY) {
|
|
183
|
+
throw new Error('mutate is disabled in read-only mode (META_ADS_READ_ONLY=true)');
|
|
184
|
+
}
|
|
185
|
+
return mutate(params);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: getPromptsList() }));
|
|
192
|
+
server.setRequestHandler(GetPromptRequestSchema, async (request) => (
|
|
193
|
+
renderPrompt(request.params.name, request.params.arguments || {})
|
|
194
|
+
));
|
|
195
|
+
|
|
196
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: getResourcesList() }));
|
|
197
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => readResource(request.params.uri));
|
|
198
|
+
|
|
199
|
+
async function main() {
|
|
200
|
+
const transport = new StdioServerTransport();
|
|
201
|
+
await server.connect(transport);
|
|
202
|
+
console.error(`${SERVER_NAME} v${SERVER_VERSION} started`);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
main().catch((error) => {
|
|
206
|
+
console.error('Fatal error:', error);
|
|
207
|
+
process.exit(1);
|
|
208
|
+
});
|