Meta Ads (Facebook/Instagram) MCP server for Claude, ChatGPT, Perplexity & Cursor — the Meta node of Pipeboard’s 5-platform family (+ Google, TikTok, Snap, Reddit). Hosted remote MCP, badged Meta Business Partner, free plan — no self-hosting required.
Python advertisingai-agentschatgptclaudefacebook-adsinstagram-adsmcpmeta-adsmodel-context-protocolpipeboard
Refactor API function signatures to require account_id and improve type hints for access_token across multiple modules. This change enhances code clarity and enforces required parameters for better error handling.
Yves Junqueira062826472591
diff --git a/meta_ads_mcp/core/accounts.py b/meta_ads_mcp/core/accounts.pyindex e9d730b..c14673f 100644--- a/meta_ads_mcp/core/accounts.py+++ b/meta_ads_mcp/core/accounts.py@@ -30,13 +30,13 @@ async def get_ad_accounts(access_token: Optional[str] = None, user_id: str = "me@mcp_server.tool()@meta_api_tool-async def get_account_info(access_token: str = None, account_id: str = None) -> str:+async def get_account_info(account_id: str, access_token: Optional[str] = None) -> str:"""Get detailed information about a specific ad account.Args:+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)access_token: Meta API access token (optional - will use cached token if not provided)- account_id: Meta Ads account ID (format: act_XXXXXXXXX) - REQUIRED"""if not account_id:return {diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.pyindex cdcb523..43f569a 100644--- a/meta_ads_mcp/core/ads.py+++ b/meta_ads_mcp/core/ads.py@@ -16,27 +16,21 @@ from .server import mcp_server@mcp_server.tool()@meta_api_tool-async def get_ads(access_token: str = None, account_id: str = None, limit: int = 10,+async def get_ads(account_id: str, access_token: Optional[str] = None, limit: int = 10,campaign_id: str = "", adset_id: str = "") -> str:"""Get ads for a Meta Ads account with optional filtering.Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ access_token: Meta API access token (optional - will use cached token if not provided)limit: Maximum number of ads to return (default: 10)campaign_id: Optional campaign ID to filter byadset_id: Optional ad set ID to filter by"""- # If no account ID is specified, try to get the first one for the user+ # Require explicit account_idif not account_id:- accounts_json = await get_ad_accounts("me", json.dumps({"limit": 1}), access_token)- accounts_data = json.loads(accounts_json)-- if "data" in accounts_data and accounts_data["data"]:- account_id = accounts_data["data"][0]["id"]- else:- return json.dumps({"error": "No account ID specified and no accounts found for user"}, indent=2)+ return json.dumps({"error": "No account ID specified"}, indent=2)# Prioritize adset_id over campaign_id - use adset-specific endpointif adset_id:@@ -67,13 +61,13 @@ async def get_ads(access_token: str = None, account_id: str = None, limit: int =@mcp_server.tool()@meta_api_tool-async def get_ad_details(access_token: str = None, ad_id: str = None) -> str:+async def get_ad_details(ad_id: str, access_token: Optional[str] = None) -> str:"""Get detailed information about a specific ad.Args:- access_token: Meta API access token (optional - will use cached token if not provided)ad_id: Meta Ads ad ID+ access_token: Meta API access token (optional - will use cached token if not provided)"""if not ad_id:return json.dumps({"error": "No ad ID provided"}, indent=2)@@ -91,14 +85,14 @@ async def get_ad_details(access_token: str = None, ad_id: str = None) -> str:@mcp_server.tool()@meta_api_toolasync def create_ad(- account_id: str = None,- name: str = None,- adset_id: str = None,- creative_id: str = None,+ account_id: str,+ name: str,+ adset_id: str,+ creative_id: str,status: str = "PAUSED",- bid_amount = None,+ bid_amount: Optional[int] = None,tracking_specs: Optional[List[Dict[str, Any]]] = None,- access_token: str = None+ access_token: Optional[str] = None) -> str:"""Create a new ad with an existing creative.@@ -158,13 +152,13 @@ async def create_ad(@mcp_server.tool()@meta_api_tool-async def get_ad_creatives(access_token: str = None, ad_id: str = None) -> str:+async def get_ad_creatives(ad_id: str, access_token: Optional[str] = None) -> str:"""Get creative details for a specific ad. Best if combined with get_ad_image to get the full image.Args:- access_token: Meta API access token (optional - will use cached token if not provided)ad_id: Meta Ads ad ID+ access_token: Meta API access token (optional - will use cached token if not provided)"""if not ad_id:return json.dumps({"error": "No ad ID provided"}, indent=2)@@ -186,13 +180,13 @@ async def get_ad_creatives(access_token: str = None, ad_id: str = None) -> str:@mcp_server.tool()@meta_api_tool-async def get_ad_image(access_token: str = None, ad_id: str = None) -> Image:+async def get_ad_image(ad_id: str, access_token: Optional[str] = None) -> Image:"""Get, download, and visualize a Meta ad image in one step. Useful to see the image in the LLM.Args:- access_token: Meta API access token (optional - will use cached token if not provided)ad_id: Meta Ads ad ID+ access_token: Meta API access token (optional - will use cached token if not provided)Returns:The ad image ready for direct visual analysis@@ -388,13 +382,13 @@ async def get_ad_image(access_token: str = None, ad_id: str = None) -> Image:@mcp_server.tool()@meta_api_tool-async def save_ad_image_locally(access_token: str = None, ad_id: str = None, output_dir: str = "ad_images") -> str:+async def save_ad_image_locally(ad_id: str, access_token: Optional[str] = None, output_dir: str = "ad_images") -> str:"""Get, download, and save a Meta ad image locally, returning the file path.Args:- access_token: Meta API access token (optional - will use cached token if not provided)ad_id: Meta Ads ad ID+ access_token: Meta API access token (optional - will use cached token if not provided)output_dir: Directory to save the image file (default: 'ad_images')Returns:@@ -516,11 +510,11 @@ async def save_ad_image_locally(access_token: str = None, ad_id: str = None, out@meta_api_toolasync def update_ad(ad_id: str,- status: str = None,- bid_amount: int = None,- tracking_specs = None,- creative_id: str = None,- access_token: str = None+ status: Optional[str] = None,+ bid_amount: Optional[int] = None,+ tracking_specs: Optional[List[Dict[str, Any]]] = None,+ creative_id: Optional[str] = None,+ access_token: Optional[str] = None) -> str:"""Update an ad with new settings.@@ -562,18 +556,18 @@ async def update_ad(@mcp_server.tool()@meta_api_toolasync def upload_ad_image(- access_token: str = None,- account_id: str = None,- file: str = None,- image_url: str = None,- name: str = None+ account_id: str,+ access_token: Optional[str] = None,+ file: Optional[str] = None,+ image_url: Optional[str] = None,+ name: Optional[str] = None) -> str:"""Upload an image to use in Meta Ads creatives.Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ access_token: Meta API access token (optional - will use cached token if not provided)file: Data URL or raw base64 string of the image (e.g., "data:image/png;base64,iVBORw0KG...")image_url: Direct URL to an image to fetch and uploadname: Optional name for the image (default: filename)@@ -731,29 +725,29 @@ async def upload_ad_image(@mcp_server.tool()@meta_api_toolasync def create_ad_creative(- access_token: str = None,- account_id: str = None,- name: str = None,- image_hash: str = None,- page_id: str = None,- link_url: str = None,- message: str = None,- headline: str = None,- headlines: List[str] = None,- description: str = None,- descriptions: List[str] = None,- dynamic_creative_spec: Dict[str, Any] = None,- call_to_action_type: str = None,- instagram_actor_id: str = None+ account_id: str,+ image_hash: str,+ access_token: Optional[str] = None,+ name: Optional[str] = None,+ page_id: Optional[str] = None,+ link_url: Optional[str] = None,+ message: Optional[str] = None,+ headline: Optional[str] = None,+ headlines: Optional[List[str]] = None,+ description: Optional[str] = None,+ descriptions: Optional[List[str]] = None,+ dynamic_creative_spec: Optional[Dict[str, Any]] = None,+ call_to_action_type: Optional[str] = None,+ instagram_actor_id: Optional[str] = None) -> str:"""Create a new ad creative using an uploaded image hash.Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)- name: Creative nameimage_hash: Hash of the uploaded image+ access_token: Meta API access token (optional - will use cached token if not provided)+ name: Creative namepage_id: Facebook Page ID to be used for the adlink_url: Destination URL for the admessage: Ad copy/text@@ -943,23 +937,23 @@ async def create_ad_creative(@mcp_server.tool()@meta_api_toolasync def update_ad_creative(- access_token: str = None,- creative_id: str = None,- name: str = None,- message: str = None,- headline: str = None,- headlines: List[str] = None,- description: str = None,- descriptions: List[str] = None,- dynamic_creative_spec: Dict[str, Any] = None,- call_to_action_type: str = None+ creative_id: str,+ access_token: Optional[str] = None,+ name: Optional[str] = None,+ message: Optional[str] = None,+ headline: Optional[str] = None,+ headlines: Optional[List[str]] = None,+ description: Optional[str] = None,+ descriptions: Optional[List[str]] = None,+ dynamic_creative_spec: Optional[Dict[str, Any]] = None,+ call_to_action_type: Optional[str] = None) -> str:"""Update an existing ad creative with new content or settings.Args:- access_token: Meta API access token (optional - will use cached token if not provided)creative_id: Meta Ads creative ID to update+ access_token: Meta API access token (optional - will use cached token if not provided)name: New creative namemessage: New ad copy/textheadline: Single headline for simple ads (cannot be used with headlines)@@ -1252,13 +1246,13 @@ async def _search_pages_by_name_core(access_token: str, account_id: str, search_@mcp_server.tool()@meta_api_tool-async def search_pages_by_name(access_token: str = None, account_id: str = None, search_term: str = None) -> str:+async def search_pages_by_name(account_id: str, access_token: Optional[str] = None, search_term: Optional[str] = None) -> str:"""Search for pages by name within an account.Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ access_token: Meta API access token (optional - will use cached token if not provided)search_term: Search term to find pages by name (optional - returns all pages if not provided)Returns:@@ -1275,13 +1269,13 @@ async def search_pages_by_name(access_token: str = None, account_id: str = None,@mcp_server.tool()@meta_api_tool-async def get_account_pages(access_token: str = None, account_id: str = None) -> str:+async def get_account_pages(account_id: str, access_token: Optional[str] = None) -> str:"""Get pages associated with a Meta Ads account.Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ access_token: Meta API access token (optional - will use cached token if not provided)Returns:JSON response with pages associated with the accountdiff --git a/meta_ads_mcp/core/ads_library.py b/meta_ads_mcp/core/ads_library.pyindex 1c8fca9..95fe26d 100644--- a/meta_ads_mcp/core/ads_library.py+++ b/meta_ads_mcp/core/ads_library.py@@ -14,10 +14,10 @@ if not DISABLE_ADS_LIBRARY:@mcp_server.tool()@meta_api_toolasync def search_ads_archive(- access_token: str = None,- search_terms: str = None,+ search_terms: str,+ ad_reached_countries: List[str],+ access_token: Optional[str] = None,ad_type: str = "ALL",- ad_reached_countries: List[str] = None,limit: int = 25, # Default limit, adjust as neededfields: str = "ad_creation_time,ad_creative_body,ad_creative_link_caption,ad_creative_link_description,ad_creative_link_title,ad_delivery_start_time,ad_delivery_stop_time,ad_snapshot_url,currency,demographic_distribution,funding_entity,impressions,page_id,page_name,publisher_platform,region_distribution,spend") -> str:@@ -25,10 +25,10 @@ if not DISABLE_ADS_LIBRARY:Search the Facebook Ads Library archive.Args:- access_token: Meta API access token (optional - will use cached token if not provided).search_terms: The search query for ads.- ad_type: Type of ads to search for (e.g., POLITICAL_AND_ISSUE_ADS, HOUSING_ADS, ALL).ad_reached_countries: List of country codes (e.g., ["US", "GB"]).+ access_token: Meta API access token (optional - will use cached token if not provided).+ ad_type: Type of ads to search for (e.g., POLITICAL_AND_ISSUE_ADS, HOUSING_ADS, ALL).limit: Maximum number of ads to return.fields: Comma-separated string of fields to retrieve for each ad.diff --git a/meta_ads_mcp/core/adsets.py b/meta_ads_mcp/core/adsets.pyindex e42c419..cb69fce 100644--- a/meta_ads_mcp/core/adsets.py+++ b/meta_ads_mcp/core/adsets.py@@ -9,25 +9,19 @@ from .server import mcp_server@mcp_server.tool()@meta_api_tool-async def get_adsets(access_token: str = None, account_id: str = None, limit: int = 10, campaign_id: str = "") -> str:+async def get_adsets(account_id: str, access_token: Optional[str] = None, limit: int = 10, campaign_id: str = "") -> str:"""Get ad sets for a Meta Ads account with optional filtering by campaign.Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ access_token: Meta API access token (optional - will use cached token if not provided)limit: Maximum number of ad sets to return (default: 10)campaign_id: Optional campaign ID to filter by"""- # If no account ID is specified, try to get the first one for the user+ # Require explicit account_idif not account_id:- accounts_json = await get_ad_accounts("me", json.dumps({"limit": 1}), access_token)- accounts_data = json.loads(accounts_json)-- if "data" in accounts_data and accounts_data["data"]:- account_id = accounts_data["data"][0]["id"]- else:- return json.dumps({"error": "No account ID specified and no accounts found for user"}, indent=2)+ return json.dumps({"error": "No account ID specified"}, indent=2)# Change endpoint based on whether campaign_id is providedif campaign_id:@@ -53,12 +47,12 @@ async def get_adsets(access_token: str = None, account_id: str = None, limit: in@mcp_server.tool()@meta_api_tool-async def get_adset_details(access_token: str = None, adset_id: str = None) -> str:+async def get_adset_details(adset_id: str, access_token: Optional[str] = None) -> str:"""Get detailed information about a specific ad set.Args:- adset_id: Meta Ads ad set ID (required)+ adset_id: Meta Ads ad set IDaccess_token: Meta API access token (optional - will use cached token if not provided)Example:@@ -90,23 +84,23 @@ async def get_adset_details(access_token: str = None, adset_id: str = None) -> s@mcp_server.tool()@meta_api_toolasync def create_adset(- account_id: str = None,- campaign_id: str = None,- name: str = None,+ account_id: str,+ campaign_id: str,+ name: str,+ optimization_goal: str,+ billing_event: str,status: str = "PAUSED",- daily_budget = None,- lifetime_budget = None,- targeting: Dict[str, Any] = None,- optimization_goal: str = None,- billing_event: str = None,- bid_amount = None,- bid_strategy: str = None,- start_time: str = None,- end_time: str = None,- dsa_beneficiary: str = None,- promoted_object: Dict[str, Any] = None,- destination_type: str = None,- access_token: str = None+ daily_budget: Optional[int] = None,+ lifetime_budget: Optional[int] = None,+ targeting: Optional[Dict[str, Any]] = None,+ bid_amount: Optional[int] = None,+ bid_strategy: Optional[str] = None,+ start_time: Optional[str] = None,+ end_time: Optional[str] = None,+ dsa_beneficiary: Optional[str] = None,+ promoted_object: Optional[Dict[str, Any]] = None,+ destination_type: Optional[str] = None,+ access_token: Optional[str] = None) -> str:"""Create a new ad set in a Meta Ads account.@@ -115,13 +109,13 @@ async def create_adset(account_id: Meta Ads account ID (format: act_XXXXXXXXX)campaign_id: Meta Ads campaign ID this ad set belongs toname: Ad set name+ optimization_goal: Conversion optimization goal (e.g., 'LINK_CLICKS', 'REACH', 'CONVERSIONS', 'APP_INSTALLS')+ billing_event: How you're charged (e.g., 'IMPRESSIONS', 'LINK_CLICKS')status: Initial ad set status (default: PAUSED)daily_budget: Daily budget in account currency (in cents) as a stringlifetime_budget: Lifetime budget in account currency (in cents) as a stringtargeting: Targeting specifications including age, location, interests, etc.Use targeting_automation.advantage_audience=1 for automatic audience finding- optimization_goal: Conversion optimization goal (e.g., 'LINK_CLICKS', 'REACH', 'CONVERSIONS', 'APP_INSTALLS')- billing_event: How you're charged (e.g., 'IMPRESSIONS', 'LINK_CLICKS')bid_amount: Bid amount in account currency (in cents)bid_strategy: Bid strategy (e.g., 'LOWEST_COST', 'LOWEST_COST_WITH_BID_CAP')start_time: Start time in ISO 8601 format (e.g., '2023-12-01T12:00:00-0800')@@ -293,10 +287,10 @@ async def create_adset(@mcp_server.tool()@meta_api_tool-async def update_adset(adset_id: str, frequency_control_specs: List[Dict[str, Any]] = None, bid_strategy: str = None,- bid_amount: int = None, status: str = None, targeting: Dict[str, Any] = None,- optimization_goal: str = None, daily_budget = None, lifetime_budget = None,- access_token: str = None) -> str:+async def update_adset(adset_id: str, frequency_control_specs: Optional[List[Dict[str, Any]]] = None, bid_strategy: Optional[str] = None,+ bid_amount: Optional[int] = None, status: Optional[str] = None, targeting: Optional[Dict[str, Any]] = None,+ optimization_goal: Optional[str] = None, daily_budget: Optional[int] = None, lifetime_budget: Optional[int] = None,+ access_token: Optional[str] = None) -> str:"""Update an ad set with new settings including frequency caps and budgets.diff --git a/meta_ads_mcp/core/api.py b/meta_ads_mcp/core/api.pyindex ab71b3b..8ff12b8 100644--- a/meta_ads_mcp/core/api.py+++ b/meta_ads_mcp/core/api.py@@ -316,6 +316,6 @@ def meta_api_tool(func):return resultexcept Exception as e:logger.error(f"Error in {func.__name__}: {str(e)}")- return {"error": str(e)}+ return json.dumps({"error": str(e)}, indent=2)return wrapper\ No newline at end of filediff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.pyindex 7cd2125..6602148 100644--- a/meta_ads_mcp/core/auth.py+++ b/meta_ads_mcp/core/auth.py@@ -87,7 +87,7 @@ meta_config = MetaConfig()class TokenInfo:"""Stores token information including expiration"""- def __init__(self, access_token: str, expires_in: int = None, user_id: str = None):+ def __init__(self, access_token: str, expires_in: Optional[int] = None, user_id: Optional[str] = None):self.access_token = access_tokenself.expires_in = expires_inself.user_id = user_iddiff --git a/meta_ads_mcp/core/authentication.py b/meta_ads_mcp/core/authentication.pyindex ae8ba1d..3161da3 100644--- a/meta_ads_mcp/core/authentication.py+++ b/meta_ads_mcp/core/authentication.py@@ -25,6 +25,7 @@ Environment Variables:"""import json+from typing import Optionalimport asyncioimport osfrom .api import meta_api_tool@@ -37,7 +38,7 @@ from .pipeboard_auth import pipeboard_auth_managerENABLE_LOGIN_LINK = not bool(os.environ.get("META_ADS_DISABLE_LOGIN_LINK", ""))-async def get_login_link(access_token: str = None) -> str:+async def get_login_link(access_token: Optional[str] = None) -> str:"""Get a clickable login link for Meta Ads authentication.diff --git a/meta_ads_mcp/core/budget_schedules.py b/meta_ads_mcp/core/budget_schedules.pyindex 62464eb..ab52574 100644--- a/meta_ads_mcp/core/budget_schedules.py+++ b/meta_ads_mcp/core/budget_schedules.py@@ -16,7 +16,7 @@ async def create_budget_schedule(budget_value_type: str,time_start: int,time_end: int,- access_token: str = None+ access_token: Optional[str] = None) -> str:"""Create a budget schedule for a Meta Ads campaign.diff --git a/meta_ads_mcp/core/campaigns.py b/meta_ads_mcp/core/campaigns.pyindex 2b1d96b..4fb6a98 100644--- a/meta_ads_mcp/core/campaigns.py+++ b/meta_ads_mcp/core/campaigns.py@@ -9,7 +9,7 @@ from .server import mcp_server@mcp_server.tool()@meta_api_tool-async def get_campaigns(access_token: str = None, account_id: str = None, limit: int = 10, status_filter: str = "", after: str = "") -> str:+async def get_campaigns(account_id: str, access_token: Optional[str] = None, limit: int = 10, status_filter: str = "", after: str = "") -> str:"""Get campaigns for a Meta Ads account with optional filtering.@@ -20,23 +20,17 @@ async def get_campaigns(access_token: str = None, account_id: str = None, limit:in the API call (currently not exposed by this tool's parameters).Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ access_token: Meta API access token (optional - will use cached token if not provided)limit: Maximum number of campaigns to return (default: 10)status_filter: Filter by effective status (e.g., 'ACTIVE', 'PAUSED', 'ARCHIVED').Maps to the 'effective_status' API parameter, which expects an array(this function handles the required JSON formatting). Leave empty for all statuses.after: Pagination cursor to get the next set of results"""- # If no account ID is specified, try to get the first one for the user+ # Require explicit account_idif not account_id:- accounts_json = await get_ad_accounts("me", json.dumps({"limit": 1}), access_token)- accounts_data = json.loads(accounts_json)-- if "data" in accounts_data and accounts_data["data"]:- account_id = accounts_data["data"][0]["id"]- else:- return json.dumps({"error": "No account ID specified and no accounts found for user"}, indent=2)+ return json.dumps({"error": "No account ID specified"}, indent=2)endpoint = f"{account_id}/campaigns"params = {@@ -58,7 +52,7 @@ async def get_campaigns(access_token: str = None, account_id: str = None, limit:@mcp_server.tool()@meta_api_tool-async def get_campaign_details(access_token: str = None, campaign_id: str = None) -> str:+async def get_campaign_details(campaign_id: str, access_token: Optional[str] = None) -> str:"""Get detailed information about a specific campaign.@@ -67,8 +61,8 @@ async def get_campaign_details(access_token: str = None, campaign_id: str = Nonethat could be added to the 'fields' parameter in the code if needed.Args:- access_token: Meta API access token (optional - will use cached token if not provided)campaign_id: Meta Ads campaign ID+ access_token: Meta API access token (optional - will use cached token if not provided)"""if not campaign_id:return json.dumps({"error": "No campaign ID provided"}, indent=2)@@ -86,19 +80,19 @@ async def get_campaign_details(access_token: str = None, campaign_id: str = None@mcp_server.tool()@meta_api_toolasync def create_campaign(- access_token: str = None,- account_id: str = None,- name: str = None,- objective: str = None,+ account_id: str,+ name: str,+ objective: str,+ access_token: Optional[str] = None,status: str = "PAUSED",- special_ad_categories: List[str] = None,- daily_budget = None,- lifetime_budget = None,- buying_type: str = None,- bid_strategy: str = None,- bid_cap = None,- spend_cap = None,- campaign_budget_optimization: bool = None,+ special_ad_categories: Optional[List[str]] = None,+ daily_budget: Optional[int] = None,+ lifetime_budget: Optional[int] = None,+ buying_type: Optional[str] = None,+ bid_strategy: Optional[str] = None,+ bid_cap: Optional[int] = None,+ spend_cap: Optional[int] = None,+ campaign_budget_optimization: Optional[bool] = None,ab_test_control_setups: Optional[List[Dict[str, Any]]] = None,use_adset_level_budgets: bool = False) -> str:@@ -106,7 +100,6 @@ async def create_campaign(Create a new campaign in a Meta Ads account.Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)name: Campaign nameobjective: Campaign objective (ODAX, outcome-based). Must be one of:@@ -116,6 +109,7 @@ async def create_campaign(CONVERSIONS, APP_INSTALLS, etc. are not valid for newcampaigns and will cause a 400 error. Use the outcome-basedvalues above (e.g., BRAND_AWARENESS → OUTCOME_AWARENESS).+ access_token: Meta API access token (optional - will use cached token if not provided)status: Initial campaign status (default: PAUSED)special_ad_categories: List of special ad categories if applicabledaily_budget: Daily budget in account currency (in cents) as a string (only used if use_adset_level_budgets=False)@@ -204,26 +198,26 @@ async def create_campaign(@mcp_server.tool()@meta_api_toolasync def update_campaign(- access_token: str = None,- campaign_id: str = None,- name: str = None,- status: str = None,- special_ad_categories: List[str] = None,- daily_budget = None,- lifetime_budget = None,- bid_strategy: str = None,- bid_cap = None,- spend_cap = None,- campaign_budget_optimization: bool = None,- objective: str = None, # Add objective if it's updatable- use_adset_level_budgets: bool = None, # Add other updatable fields as needed based on API docs+ campaign_id: str,+ access_token: Optional[str] = None,+ name: Optional[str] = None,+ status: Optional[str] = None,+ special_ad_categories: Optional[List[str]] = None,+ daily_budget: Optional[int] = None,+ lifetime_budget: Optional[int] = None,+ bid_strategy: Optional[str] = None,+ bid_cap: Optional[int] = None,+ spend_cap: Optional[int] = None,+ campaign_budget_optimization: Optional[bool] = None,+ objective: Optional[str] = None, # Add objective if it's updatable+ use_adset_level_budgets: Optional[bool] = None, # Add other updatable fields as needed based on API docs) -> str:"""Update an existing campaign in a Meta Ads account.Args:+ campaign_id: Meta Ads campaign IDaccess_token: Meta API access token (optional - will use cached token if not provided)- campaign_id: Meta Ads campaign ID (required)name: New campaign namestatus: New campaign status (e.g., 'ACTIVE', 'PAUSED')special_ad_categories: List of special ad categories if applicablediff --git a/meta_ads_mcp/core/duplication.py b/meta_ads_mcp/core/duplication.pyindex e6b18ec..7318659 100644--- a/meta_ads_mcp/core/duplication.py+++ b/meta_ads_mcp/core/duplication.py@@ -18,7 +18,7 @@ if ENABLE_DUPLICATION:@meta_api_toolasync def duplicate_campaign(campaign_id: str,- access_token: str = None,+ access_token: Optional[str] = None,name_suffix: Optional[str] = " - Copy",include_ad_sets: bool = True,include_ads: bool = True,@@ -61,7 +61,7 @@ if ENABLE_DUPLICATION:@meta_api_toolasync def duplicate_adset(adset_id: str,- access_token: str = None,+ access_token: Optional[str] = None,target_campaign_id: Optional[str] = None,name_suffix: Optional[str] = " - Copy",include_ads: bool = True,@@ -104,7 +104,7 @@ if ENABLE_DUPLICATION:@meta_api_toolasync def duplicate_ad(ad_id: str,- access_token: str = None,+ access_token: Optional[str] = None,target_adset_id: Optional[str] = None,name_suffix: Optional[str] = " - Copy",duplicate_creative: bool = True,@@ -141,7 +141,7 @@ if ENABLE_DUPLICATION:@meta_api_toolasync def duplicate_creative(creative_id: str,- access_token: str = None,+ access_token: Optional[str] = None,name_suffix: Optional[str] = " - Copy",new_primary_text: Optional[str] = None,new_headline: Optional[str] = None,diff --git a/meta_ads_mcp/core/insights.py b/meta_ads_mcp/core/insights.pyindex 8dd5ddc..d06c46a 100644--- a/meta_ads_mcp/core/insights.py+++ b/meta_ads_mcp/core/insights.py@@ -11,15 +11,15 @@ import datetime@mcp_server.tool()@meta_api_tool-async def get_insights(access_token: str = None, object_id: str = None,+async def get_insights(object_id: str, access_token: Optional[str] = None,time_range: Union[str, Dict[str, str]] = "maximum", breakdown: str = "",level: str = "ad") -> str:"""Get performance insights for a campaign, ad set, ad or account.Args:- access_token: Meta API access token (optional - will use cached token if not provided)object_id: ID of the campaign, ad set, ad or account+ access_token: Meta API access token (optional - will use cached token if not provided)time_range: Either a preset time range string or a dictionary with "since" and "until" dates in YYYY-MM-DD formatPreset options: today, yesterday, this_month, last_month, this_quarter, maximum, data_maximum,last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, last_week_mon_sun,diff --git a/meta_ads_mcp/core/openai_deep_research.py b/meta_ads_mcp/core/openai_deep_research.pyindex 2075118..7ecfa00 100644--- a/meta_ads_mcp/core/openai_deep_research.py+++ b/meta_ads_mcp/core/openai_deep_research.py@@ -310,8 +310,8 @@ _data_manager = MetaAdsDataManager()@mcp_server.tool()@meta_api_toolasync def search(- access_token: str = None,- query: str = None+ query: str,+ access_token: Optional[str] = None) -> str:"""Search through Meta Ads data and return matching record IDs.@@ -321,8 +321,8 @@ async def search(based on the provided query.Args:- access_token: Meta API access token (optional - will use cached token if not provided)query: Search query string to find relevant Meta Ads records+ access_token: Meta API access token (optional - will use cached token if not provided)Returns:JSON response with list of matching record IDs@@ -367,7 +367,7 @@ async def search(@mcp_server.tool()async def fetch(- id: str = None+ id: str) -> str:"""Fetch complete record data by ID.diff --git a/meta_ads_mcp/core/pipeboard_auth.py b/meta_ads_mcp/core/pipeboard_auth.pyindex 69ee39d..754961e 100644--- a/meta_ads_mcp/core/pipeboard_auth.py+++ b/meta_ads_mcp/core/pipeboard_auth.py@@ -21,7 +21,7 @@ logger.info(f"Pipeboard API base URL: {PIPEBOARD_API_BASE}")class TokenInfo:"""Stores token information including expiration"""- def __init__(self, access_token: str, expires_at: str = None, token_type: str = None):+ def __init__(self, access_token: str, expires_at: Optional[str] = None, token_type: Optional[str] = None):self.access_token = access_tokenself.expires_at = expires_atself.token_type = token_typediff --git a/meta_ads_mcp/core/reports.py b/meta_ads_mcp/core/reports.pyindex c517a80..87536bc 100644--- a/meta_ads_mcp/core/reports.py+++ b/meta_ads_mcp/core/reports.py@@ -13,8 +13,8 @@ ENABLE_REPORT_GENERATION = bool(os.environ.get("META_ADS_ENABLE_REPORTS", ""))if ENABLE_REPORT_GENERATION:@mcp_server.tool()async def generate_report(- access_token: str = None,- account_id: str = None,+ account_id: str,+ access_token: Optional[str] = None,report_type: str = "account",time_range: str = "last_30d",campaign_ids: Optional[List[str]] = None,@@ -30,8 +30,8 @@ if ENABLE_REPORT_GENERATION:**This is a premium feature available with Pipeboard Pro.**Args:- access_token: Meta API access token (optional - will use cached token if not provided)account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ access_token: Meta API access token (optional - will use cached token if not provided)report_type: Type of report to generate (account, campaign, comparison)time_range: Time period for the report (e.g., 'last_30d', 'last_7d', 'this_month')campaign_ids: Specific campaign IDs (required for campaign/comparison reports)diff --git a/meta_ads_mcp/core/targeting.py b/meta_ads_mcp/core/targeting.pyindex 85283d7..b50391e 100644--- a/meta_ads_mcp/core/targeting.py+++ b/meta_ads_mcp/core/targeting.py@@ -8,13 +8,13 @@ from .server import mcp_server@mcp_server.tool()@meta_api_tool-async def search_interests(access_token: str = None, query: str = None, limit: int = 25) -> str:+async def search_interests(query: str, access_token: Optional[str] = None, limit: int = 25) -> str:"""Search for interest targeting options by keyword.Args:- access_token: Meta API access token (optional - will use cached token if not provided)query: Search term for interests (e.g., "baseball", "cooking", "travel")+ access_token: Meta API access token (optional - will use cached token if not provided)limit: Maximum number of results to return (default: 25)Returns:@@ -37,13 +37,13 @@ async def search_interests(access_token: str = None, query: str = None, limit: i@mcp_server.tool()@meta_api_tool-async def get_interest_suggestions(access_token: str = None, interest_list: List[str] = None, limit: int = 25) -> str:+async def get_interest_suggestions(interest_list: List[str], access_token: Optional[str] = None, limit: int = 25) -> str:"""Get interest suggestions based on existing interests.Args:- access_token: Meta API access token (optional - will use cached token if not provided)interest_list: List of interest names to get suggestions for (e.g., ["Basketball", "Soccer"])+ access_token: Meta API access token (optional - will use cached token if not provided)limit: Maximum number of suggestions to return (default: 25)Returns:@@ -67,13 +67,13 @@ async def get_interest_suggestions(access_token: str = None, interest_list: List@mcp_server.tool()@meta_api_toolasync def estimate_audience_size(- access_token: str = None,- account_id: str = None,- targeting: Dict[str, Any] = None,+ access_token: Optional[str] = None,+ account_id: Optional[str] = None,+ targeting: Optional[Dict[str, Any]] = None,optimization_goal: str = "REACH",# Backwards compatibility for simple interest validation- interest_list: List[str] = None,- interest_fbid_list: List[str] = None+ interest_list: Optional[List[str]] = None,+ interest_fbid_list: Optional[List[str]] = None) -> str:"""Estimate audience size for targeting specifications using Meta's delivery_estimate API.@@ -247,7 +247,7 @@ async def estimate_audience_size(@mcp_server.tool()@meta_api_tool-async def search_behaviors(access_token: str = None, limit: int = 50) -> str:+async def search_behaviors(access_token: Optional[str] = None, limit: int = 50) -> str:"""Get all available behavior targeting options.@@ -272,7 +272,7 @@ async def search_behaviors(access_token: str = None, limit: int = 50) -> str:@mcp_server.tool()@meta_api_tool-async def search_demographics(access_token: str = None, demographic_class: str = "demographics", limit: int = 50) -> str:+async def search_demographics(access_token: Optional[str] = None, demographic_class: str = "demographics", limit: int = 50) -> str:"""Get demographic targeting options.@@ -299,14 +299,14 @@ async def search_demographics(access_token: str = None, demographic_class: str =@mcp_server.tool()@meta_api_tool-async def search_geo_locations(access_token: str = None, query: str = None,- location_types: List[str] = None, limit: int = 25) -> str:+async def search_geo_locations(query: str, access_token: Optional[str] = None,+ location_types: Optional[List[str]] = None, limit: int = 25) -> str:"""Search for geographic targeting locations.Args:- access_token: Meta API access token (optional - will use cached token if not provided)query: Search term for locations (e.g., "New York", "California", "Japan")+ access_token: Meta API access token (optional - will use cached token if not provided)location_types: Types of locations to search. Options: ['country', 'region', 'city', 'zip','geo_market', 'electoral_district']. If not specified, searches all types.limit: Maximum number of results to return (default: 25)diff --git a/tests/test_dsa_beneficiary.py b/tests/test_dsa_beneficiary.pyindex 3230360..c3dec9a 100644--- a/tests/test_dsa_beneficiary.py+++ b/tests/test_dsa_beneficiary.py@@ -104,7 +104,7 @@ class TestDSABeneficiaryDetection:mock_auth.return_value = "test_access_token"# Test without account_id parameter- result = await get_account_info()+ result = await get_account_info(account_id=None)# Handle new return format (dictionary instead of JSON string)if isinstance(result, dict):diff --git a/tests/test_dsa_integration.py b/tests/test_dsa_integration.pyindex 3bb945e..2f6197d 100644--- a/tests/test_dsa_integration.py+++ b/tests/test_dsa_integration.py@@ -402,7 +402,7 @@ class TestDSAIntegration:mock_auth.return_value = "test_access_token"# Test without account_id parameter- result = await get_account_info()+ result = await get_account_info(account_id=None)# Handle new return format (dictionary instead of JSON string)if isinstance(result, dict):diff --git a/tests/test_dynamic_creatives.py b/tests/test_dynamic_creatives.pyindex ee99e2e..89d4b30 100644--- a/tests/test_dynamic_creatives.py+++ b/tests/test_dynamic_creatives.py@@ -502,9 +502,10 @@ class TestDynamicCreatives:assert creative_data["dynamic_creative_spec"]["description_optimization"] is Falseasync def test_update_ad_creative_no_creative_id(self):- """Test update_ad_creative with no creative_id provided."""+ """Test update_ad_creative with empty creative_id provided."""result = await update_ad_creative(+ creative_id="", # Now provide the required parameter but with empty valueaccess_token="test_token",headlines=["New Headline"])diff --git a/tests/test_insights_actions_and_values.py b/tests/test_insights_actions_and_values.pyindex 805b148..df5ce93 100644--- a/tests/test_insights_actions_and_values.py+++ b/tests/test_insights_actions_and_values.py@@ -260,17 +260,14 @@ class TestInsightsActionsAndValues:level="campaign")- # Parse the result- result_data = json.loads(result)-- # The error response is wrapped in a 'data' field- if 'data' in result_data:- error_data = json.loads(result_data['data'])- assert 'error' in error_data- assert 'No object ID provided' in error_data['error']+ # Parse the result. The decorator returns a dict error for missing required args+ if isinstance(result, dict):+ result_data = resultelse:- assert 'error' in result_data- assert 'No object ID provided' in result_data['error']+ result_data = json.loads(result)++ assert 'error' in result_data+ assert "missing 1 required positional argument: 'object_id'" in result_data['error']# Verify API was not calledmock_api_request.assert_not_called()diff --git a/tests/test_targeting.py b/tests/test_targeting.pyindex e862aa2..8380adf 100644--- a/tests/test_targeting.py+++ b/tests/test_targeting.py@@ -64,8 +64,11 @@ class TestSearchInterests:@pytest.mark.asyncioasync def test_search_interests_no_query(self):- """Test search_interests with no query provided"""- result = await search_interests(access_token="test_token")+ """Test search_interests with empty query parameter"""+ result = await search_interests(+ query="", # Now provide the required parameter but with empty value+ access_token="test_token"+ )result_data = json.loads(result)# The @meta_api_tool decorator wraps errors in a 'data' field@@ -155,8 +158,11 @@ class TestGetInterestSuggestions:@pytest.mark.asyncioasync def test_get_interest_suggestions_no_list(self):- """Test get_interest_suggestions with no interest list"""- result = await get_interest_suggestions(access_token="test_token")+ """Test get_interest_suggestions with empty interest list"""+ result = await get_interest_suggestions(+ interest_list=[], # Now provide the required parameter but with empty value+ access_token="test_token"+ )result_data = json.loads(result)# The @meta_api_tool decorator wraps errors in a 'data' field@@ -400,8 +406,11 @@ class TestSearchGeoLocations:@pytest.mark.asyncioasync def test_search_geo_locations_no_query(self):- """Test search_geo_locations with no query"""- result = await search_geo_locations(access_token="test_token")+ """Test search_geo_locations with empty query"""+ result = await search_geo_locations(+ query="", # Now provide the required parameter but with empty value+ access_token="test_token"+ )result_data = json.loads(result)# The @meta_api_tool decorator wraps errors in a 'data' field