meta-ads-mcp 0.2.8__tar.gz → 0.2.9__tar.gz

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.
Files changed (36) hide show
  1. meta_ads_mcp-0.2.9/LICENSE +201 -0
  2. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/PKG-INFO +8 -3
  3. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/README.md +6 -2
  4. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/__init__.py +1 -1
  5. meta_ads_mcp-0.2.9/meta_ads_mcp/core/ads.py +357 -0
  6. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/adsets.py +130 -9
  7. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/auth.py +2 -2
  8. meta_ads_mcp-0.2.9/meta_ads_mcp/core/campaigns.py +260 -0
  9. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/insights.py +18 -4
  10. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/pyproject.toml +1 -1
  11. meta_ads_mcp-0.2.8/meta_ads_mcp/core/ads.py +0 -426
  12. meta_ads_mcp-0.2.8/meta_ads_mcp/core/campaigns.py +0 -123
  13. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/.gitignore +0 -0
  14. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/META_API_NOTES.md +0 -0
  15. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/debug_meta_api_tool.py +0 -0
  16. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/debug_token_flow.py +0 -0
  17. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/future_improvements.md +0 -0
  18. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/images/meta-ads-example.png +0 -0
  19. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta-ads-mcp +0 -0
  20. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_auth.sh +0 -0
  21. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/__main__.py +0 -0
  22. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/api.py +0 -0
  23. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/__init__.py +0 -0
  24. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/accounts.py +0 -0
  25. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/api.py +0 -0
  26. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/authentication.py +0 -0
  27. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/callback_server.py +0 -0
  28. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/pipeboard_auth.py +0 -0
  29. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/resources.py +0 -0
  30. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/server.py +0 -0
  31. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_ads_mcp/core/utils.py +0 -0
  32. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/meta_auth_test.sh +0 -0
  33. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/requirements.txt +0 -0
  34. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/setup.py +0 -0
  35. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/test_meta_ads_auth.py +0 -0
  36. {meta_ads_mcp-0.2.8 → meta_ads_mcp-0.2.9}/test_pipeboard_auth.py +0 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: meta-ads-mcp
3
- Version: 0.2.8
3
+ Version: 0.2.9
4
4
  Summary: Model Calling Protocol (MCP) plugin for interacting with Meta Ads API
5
5
  Project-URL: Homepage, https://github.com/nictuku/meta-ads-mcp
6
6
  Project-URL: Bug Tracker, https://github.com/nictuku/meta-ads-mcp/issues
7
7
  Author-email: Your Name <your.email@example.com>
8
8
  License: MIT
9
+ License-File: LICENSE
9
10
  Keywords: ads,api,claude,facebook,mcp,meta
10
11
  Classifier: License :: OSI Approved :: MIT License
11
12
  Classifier: Operating System :: OS Independent
@@ -26,6 +27,10 @@ A [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server for in
26
27
 
27
28
  > **DISCLAIMER:** This is an unofficial third-party tool and is not associated with, endorsed by, or affiliated with Meta in any way. This project is maintained independently and uses Meta's public APIs according to their terms of service. Meta, Facebook, Instagram, and other Meta brand names are trademarks of their respective owners.
28
29
 
30
+ <a href="https://glama.ai/mcp/servers/@pipeboard-co/meta-ads-mcp">
31
+ <img width="380" height="200" src="https://glama.ai/mcp/servers/@pipeboard-co/meta-ads-mcp/badge" alt="Meta Ads MCP server" />
32
+ </a>
33
+
29
34
  Screenhot: using an LLM to understand your ad performance.
30
35
 
31
36
  ![Meta Ads MCP in action: Visualize ad performance metrics and creative details directly in Claude or your favorite MCP client, with rich insights about campaign reach, engagement, and costs](./images/meta-ads-example.png)
@@ -108,9 +113,9 @@ The easiest way to configure Meta Ads MCP is using Pipeboard authentication:
108
113
 
109
114
  This method provides longer-lived tokens (60 days), simplified setup, and automatic token renewal.
110
115
 
111
- ### Usage with Claude in Cursor
116
+ ### Usage with Cursor or Claude Desktop
112
117
 
113
- Add this to your `claude_desktop_config.json` to integrate with Claude in Cursor:
118
+ Add this to your `claude_desktop_config.json` to integrate with Claude or `~/.cursor/mcp.json` to integrate with Cursor:
114
119
 
115
120
  ```json
116
121
  "mcpServers": {
@@ -4,6 +4,10 @@ A [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server for in
4
4
 
5
5
  > **DISCLAIMER:** This is an unofficial third-party tool and is not associated with, endorsed by, or affiliated with Meta in any way. This project is maintained independently and uses Meta's public APIs according to their terms of service. Meta, Facebook, Instagram, and other Meta brand names are trademarks of their respective owners.
6
6
 
7
+ <a href="https://glama.ai/mcp/servers/@pipeboard-co/meta-ads-mcp">
8
+ <img width="380" height="200" src="https://glama.ai/mcp/servers/@pipeboard-co/meta-ads-mcp/badge" alt="Meta Ads MCP server" />
9
+ </a>
10
+
7
11
  Screenhot: using an LLM to understand your ad performance.
8
12
 
9
13
  ![Meta Ads MCP in action: Visualize ad performance metrics and creative details directly in Claude or your favorite MCP client, with rich insights about campaign reach, engagement, and costs](./images/meta-ads-example.png)
@@ -86,9 +90,9 @@ The easiest way to configure Meta Ads MCP is using Pipeboard authentication:
86
90
 
87
91
  This method provides longer-lived tokens (60 days), simplified setup, and automatic token renewal.
88
92
 
89
- ### Usage with Claude in Cursor
93
+ ### Usage with Cursor or Claude Desktop
90
94
 
91
- Add this to your `claude_desktop_config.json` to integrate with Claude in Cursor:
95
+ Add this to your `claude_desktop_config.json` to integrate with Claude or `~/.cursor/mcp.json` to integrate with Cursor:
92
96
 
93
97
  ```json
94
98
  "mcpServers": {
@@ -7,7 +7,7 @@ with the Claude LLM.
7
7
 
8
8
  from meta_ads_mcp.core.server import main
9
9
 
10
- __version__ = "0.2.8"
10
+ __version__ = "0.2.9"
11
11
 
12
12
  __all__ = [
13
13
  'get_ad_accounts',
@@ -0,0 +1,357 @@
1
+ """Ad and Creative-related functionality for Meta Ads API."""
2
+
3
+ import json
4
+ from typing import Optional, Dict, Any, List
5
+ import io
6
+ from PIL import Image as PILImage
7
+ from mcp.server.fastmcp import Image
8
+
9
+ from .api import meta_api_tool, make_api_request
10
+ from .accounts import get_ad_accounts
11
+ from .utils import download_image, try_multiple_download_methods, ad_creative_images
12
+ from .server import mcp_server
13
+
14
+
15
+ @mcp_server.tool()
16
+ @meta_api_tool
17
+ async def get_ads(access_token: str = None, account_id: str = None, limit: int = 10,
18
+ campaign_id: str = "", adset_id: str = "") -> str:
19
+ """
20
+ Get ads for a Meta Ads account with optional filtering.
21
+
22
+ Args:
23
+ access_token: Meta API access token (optional - will use cached token if not provided)
24
+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)
25
+ limit: Maximum number of ads to return (default: 10)
26
+ campaign_id: Optional campaign ID to filter by
27
+ adset_id: Optional ad set ID to filter by
28
+ """
29
+ # If no account ID is specified, try to get the first one for the user
30
+ if not account_id:
31
+ accounts_json = await get_ad_accounts("me", json.dumps({"limit": 1}), access_token)
32
+ accounts_data = json.loads(accounts_json)
33
+
34
+ if "data" in accounts_data and accounts_data["data"]:
35
+ account_id = accounts_data["data"][0]["id"]
36
+ else:
37
+ return json.dumps({"error": "No account ID specified and no accounts found for user"}, indent=2)
38
+
39
+ # Use campaign-specific endpoint if campaign_id is provided
40
+ if campaign_id:
41
+ endpoint = f"{campaign_id}/ads"
42
+ params = {
43
+ "fields": "id,name,adset_id,campaign_id,status,creative,created_time,updated_time,bid_amount,conversion_domain,tracking_specs",
44
+ "limit": limit
45
+ }
46
+ # Adset ID can still be used to filter within the campaign
47
+ if adset_id:
48
+ params["adset_id"] = adset_id
49
+ else:
50
+ # Default to account-level endpoint if no campaign_id
51
+ endpoint = f"{account_id}/ads"
52
+ params = {
53
+ "fields": "id,name,adset_id,campaign_id,status,creative,created_time,updated_time,bid_amount,conversion_domain,tracking_specs",
54
+ "limit": limit
55
+ }
56
+ # Adset ID can filter at the account level if no campaign specified
57
+ if adset_id:
58
+ params["adset_id"] = adset_id
59
+
60
+ data = await make_api_request(endpoint, access_token, params)
61
+
62
+ return json.dumps(data, indent=2)
63
+
64
+
65
+ @mcp_server.tool()
66
+ @meta_api_tool
67
+ async def get_ad_details(access_token: str = None, ad_id: str = None) -> str:
68
+ """
69
+ Get detailed information about a specific ad.
70
+
71
+ Args:
72
+ access_token: Meta API access token (optional - will use cached token if not provided)
73
+ ad_id: Meta Ads ad ID
74
+ """
75
+ if not ad_id:
76
+ return json.dumps({"error": "No ad ID provided"}, indent=2)
77
+
78
+ endpoint = f"{ad_id}"
79
+ params = {
80
+ "fields": "id,name,adset_id,campaign_id,status,creative,created_time,updated_time,bid_amount,conversion_domain,tracking_specs,preview_shareable_link"
81
+ }
82
+
83
+ data = await make_api_request(endpoint, access_token, params)
84
+
85
+ return json.dumps(data, indent=2)
86
+
87
+
88
+ @mcp_server.tool()
89
+ @meta_api_tool
90
+ async def create_ad(
91
+ account_id: str = None,
92
+ name: str = None,
93
+ adset_id: str = None,
94
+ creative_id: str = None,
95
+ status: str = "PAUSED",
96
+ bid_amount = None,
97
+ tracking_specs: Optional[List[Dict[str, Any]]] = None,
98
+ access_token: str = None
99
+ ) -> str:
100
+ """
101
+ Create a new ad with an existing creative.
102
+
103
+ Args:
104
+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)
105
+ name: Ad name
106
+ adset_id: Ad set ID where this ad will be placed
107
+ creative_id: ID of an existing creative to use
108
+ status: Initial ad status (default: PAUSED)
109
+ bid_amount: Optional bid amount in account currency (in cents)
110
+ tracking_specs: Optional tracking specifications (e.g., for pixel events).
111
+ Example: [{"action.type":"offsite_conversion","fb_pixel":["YOUR_PIXEL_ID"]}]
112
+ access_token: Meta API access token (optional - will use cached token if not provided)
113
+ """
114
+ # Check required parameters
115
+ if not account_id:
116
+ return json.dumps({"error": "No account ID provided"}, indent=2)
117
+
118
+ if not name:
119
+ return json.dumps({"error": "No ad name provided"}, indent=2)
120
+
121
+ if not adset_id:
122
+ return json.dumps({"error": "No ad set ID provided"}, indent=2)
123
+
124
+ if not creative_id:
125
+ return json.dumps({"error": "No creative ID provided"}, indent=2)
126
+
127
+ endpoint = f"{account_id}/ads"
128
+
129
+ params = {
130
+ "name": name,
131
+ "adset_id": adset_id,
132
+ "creative": {"creative_id": creative_id},
133
+ "status": status
134
+ }
135
+
136
+ # Add bid amount if provided
137
+ if bid_amount is not None:
138
+ params["bid_amount"] = str(bid_amount)
139
+
140
+ # Add tracking specs if provided
141
+ if tracking_specs is not None:
142
+ params["tracking_specs"] = json.dumps(tracking_specs) # Needs to be JSON encoded string
143
+
144
+ try:
145
+ data = await make_api_request(endpoint, access_token, params, method="POST")
146
+ return json.dumps(data, indent=2)
147
+ except Exception as e:
148
+ error_msg = str(e)
149
+ return json.dumps({
150
+ "error": "Failed to create ad",
151
+ "details": error_msg,
152
+ "params_sent": params
153
+ }, indent=2)
154
+
155
+
156
+ @mcp_server.tool()
157
+ @meta_api_tool
158
+ async def get_ad_creatives(access_token: str = None, ad_id: str = None) -> str:
159
+ """
160
+ Get creative details for a specific ad. Best if combined with get_ad_image to get the full image.
161
+
162
+ Args:
163
+ access_token: Meta API access token (optional - will use cached token if not provided)
164
+ ad_id: Meta Ads ad ID
165
+ """
166
+ if not ad_id:
167
+ return json.dumps({"error": "No ad ID provided"}, indent=2)
168
+
169
+ endpoint = f"{ad_id}/adcreatives"
170
+ params = {
171
+ "fields": "id,name,status,thumbnail_url,image_url,image_hash,object_story_spec" # Added image_hash
172
+ }
173
+
174
+ data = await make_api_request(endpoint, access_token, params)
175
+
176
+ # Add image URLs for direct viewing if available
177
+ if 'data' in data:
178
+ for creative in data['data']:
179
+ creative['image_urls_for_viewing'] = ad_creative_images(creative)
180
+
181
+ return json.dumps(data, indent=2)
182
+
183
+
184
+ @mcp_server.tool()
185
+ @meta_api_tool
186
+ async def get_ad_image(access_token: str = None, ad_id: str = None) -> Image:
187
+ """
188
+ Get, download, and visualize a Meta ad image in one step. Useful to see the image in the LLM.
189
+
190
+ Args:
191
+ access_token: Meta API access token (optional - will use cached token if not provided)
192
+ ad_id: Meta Ads ad ID
193
+
194
+ Returns:
195
+ The ad image ready for direct visual analysis
196
+ """
197
+ if not ad_id:
198
+ return "Error: No ad ID provided"
199
+
200
+ print(f"Attempting to get and analyze creative image for ad {ad_id}")
201
+
202
+ # First, get creative and account IDs
203
+ ad_endpoint = f"{ad_id}"
204
+ ad_params = {
205
+ "fields": "creative{id},account_id"
206
+ }
207
+
208
+ ad_data = await make_api_request(ad_endpoint, access_token, ad_params)
209
+
210
+ if "error" in ad_data:
211
+ return f"Error: Could not get ad data - {json.dumps(ad_data)}"
212
+
213
+ # Extract account_id
214
+ account_id = ad_data.get("account_id", "")
215
+ if not account_id:
216
+ return "Error: No account ID found"
217
+
218
+ # Extract creative ID
219
+ if "creative" not in ad_data:
220
+ return "Error: No creative found for this ad"
221
+
222
+ creative_data = ad_data.get("creative", {})
223
+ creative_id = creative_data.get("id")
224
+ if not creative_id:
225
+ return "Error: No creative ID found"
226
+
227
+ # Get creative details to find image hash
228
+ creative_endpoint = f"{creative_id}"
229
+ creative_params = {
230
+ "fields": "id,name,image_hash,asset_feed_spec"
231
+ }
232
+
233
+ creative_details = await make_api_request(creative_endpoint, access_token, creative_params)
234
+
235
+ # Identify image hashes to use from creative
236
+ image_hashes = []
237
+
238
+ # Check for direct image_hash on creative
239
+ if "image_hash" in creative_details:
240
+ image_hashes.append(creative_details["image_hash"])
241
+
242
+ # Check asset_feed_spec for image hashes - common in Advantage+ ads
243
+ if "asset_feed_spec" in creative_details and "images" in creative_details["asset_feed_spec"]:
244
+ for image in creative_details["asset_feed_spec"]["images"]:
245
+ if "hash" in image:
246
+ image_hashes.append(image["hash"])
247
+
248
+ if not image_hashes:
249
+ # If no hashes found, try to extract from the first creative we found in the API
250
+ # Get creative for ad to try to extract hash
251
+ creative_json = await get_ad_creatives(ad_id, "", access_token)
252
+ creative_data = json.loads(creative_json)
253
+
254
+ # Try to extract hash from asset_feed_spec
255
+ if "asset_feed_spec" in creative_data and "images" in creative_data["asset_feed_spec"]:
256
+ images = creative_data["asset_feed_spec"]["images"]
257
+ if images and len(images) > 0 and "hash" in images[0]:
258
+ image_hashes.append(images[0]["hash"])
259
+
260
+ if not image_hashes:
261
+ return "Error: No image hashes found in creative"
262
+
263
+ print(f"Found image hashes: {image_hashes}")
264
+
265
+ # Now fetch image data using adimages endpoint with specific format
266
+ image_endpoint = f"act_{account_id}/adimages"
267
+
268
+ # Format the hashes parameter exactly as in our successful curl test
269
+ hashes_str = f'["{image_hashes[0]}"]' # Format first hash only, as JSON string array
270
+
271
+ image_params = {
272
+ "fields": "hash,url,width,height,name,status",
273
+ "hashes": hashes_str
274
+ }
275
+
276
+ print(f"Requesting image data with params: {image_params}")
277
+ image_data = await make_api_request(image_endpoint, access_token, image_params)
278
+
279
+ if "error" in image_data:
280
+ return f"Error: Failed to get image data - {json.dumps(image_data)}"
281
+
282
+ if "data" not in image_data or not image_data["data"]:
283
+ return "Error: No image data returned from API"
284
+
285
+ # Get the first image URL
286
+ first_image = image_data["data"][0]
287
+ image_url = first_image.get("url")
288
+
289
+ if not image_url:
290
+ return "Error: No valid image URL found"
291
+
292
+ print(f"Downloading image from URL: {image_url}")
293
+
294
+ # Download the image
295
+ image_bytes = await download_image(image_url)
296
+
297
+ if not image_bytes:
298
+ return "Error: Failed to download image"
299
+
300
+ try:
301
+ # Convert bytes to PIL Image
302
+ img = PILImage.open(io.BytesIO(image_bytes))
303
+
304
+ # Convert to RGB if needed
305
+ if img.mode != "RGB":
306
+ img = img.convert("RGB")
307
+
308
+ # Create a byte stream of the image data
309
+ byte_arr = io.BytesIO()
310
+ img.save(byte_arr, format="JPEG")
311
+ img_bytes = byte_arr.getvalue()
312
+
313
+ # Return as an Image object that LLM can directly analyze
314
+ return Image(data=img_bytes, format="jpeg")
315
+
316
+ except Exception as e:
317
+ return f"Error processing image: {str(e)}"
318
+
319
+
320
+ @mcp_server.tool()
321
+ @meta_api_tool
322
+ async def update_ad(
323
+ ad_id: str,
324
+ status: str = None,
325
+ bid_amount: int = None,
326
+ tracking_specs = None,
327
+ access_token: str = None
328
+ ) -> str:
329
+ """
330
+ Update an ad with new settings.
331
+
332
+ Args:
333
+ ad_id: Meta Ads ad ID
334
+ status: Update ad status (ACTIVE, PAUSED, etc.)
335
+ bid_amount: Bid amount in account currency (in cents for USD)
336
+ tracking_specs: Optional tracking specifications (e.g., for pixel events).
337
+ access_token: Meta API access token (optional - will use cached token if not provided)
338
+ """
339
+ if not ad_id:
340
+ return json.dumps({"error": "Ad ID is required"}, indent=2)
341
+
342
+ params = {}
343
+ if status:
344
+ params["status"] = status
345
+ if bid_amount is not None:
346
+ # Ensure bid_amount is sent as a string if it's not null
347
+ params["bid_amount"] = str(bid_amount)
348
+ if tracking_specs is not None: # Add tracking_specs to params if provided
349
+ params["tracking_specs"] = json.dumps(tracking_specs) # Needs to be JSON encoded string
350
+
351
+ if not params:
352
+ return json.dumps({"error": "No update parameters provided (status, bid_amount, or tracking_specs)"}, indent=2)
353
+
354
+ endpoint = f"{ad_id}"
355
+ data = await make_api_request(endpoint, access_token, params, method='POST')
356
+
357
+ return json.dumps(data, indent=2)