google-ads-mcp-python 0.1.0__py3-none-any.whl
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.
- google_ads_mcp_python/__init__.py +0 -0
- google_ads_mcp_python/coordinator.py +24 -0
- google_ads_mcp_python/gaql_resources.txt +8190 -0
- google_ads_mcp_python/mcp_header_interceptor.py +95 -0
- google_ads_mcp_python/server.py +31 -0
- google_ads_mcp_python/tools/core.py +38 -0
- google_ads_mcp_python/tools/search.py +126 -0
- google_ads_mcp_python/update_references.py +91 -0
- google_ads_mcp_python/utils.py +140 -0
- google_ads_mcp_python-0.1.0.dist-info/METADATA +10 -0
- google_ads_mcp_python-0.1.0.dist-info/RECORD +13 -0
- google_ads_mcp_python-0.1.0.dist-info/WHEEL +4 -0
- google_ads_mcp_python-0.1.0.dist-info/entry_points.txt +4 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
# Copyright 2025 Google LLC.
|
|
4
|
+
#
|
|
5
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# you may not use this file except in compliance with the License.
|
|
7
|
+
# You may obtain a copy of the License at
|
|
8
|
+
#
|
|
9
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
#
|
|
11
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# See the License for the specific language governing permissions and
|
|
15
|
+
# limitations under the License.
|
|
16
|
+
|
|
17
|
+
import grpc
|
|
18
|
+
import logging
|
|
19
|
+
from importlib import metadata
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MCPHeaderInterceptor(
|
|
25
|
+
grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor
|
|
26
|
+
):
|
|
27
|
+
"""A custom metadata interceptor to add the 'google-ads-mcp' header."""
|
|
28
|
+
|
|
29
|
+
_API_CLIENT_HEADER = "x-goog-api-client"
|
|
30
|
+
|
|
31
|
+
def _get_package_version_with_fallback():
|
|
32
|
+
"""Returns the version of the package.
|
|
33
|
+
|
|
34
|
+
Falls back to 'unknown' if the version can't be resolved.
|
|
35
|
+
"""
|
|
36
|
+
try:
|
|
37
|
+
return metadata.version("google-ads-mcp")
|
|
38
|
+
except:
|
|
39
|
+
return "unknown"
|
|
40
|
+
|
|
41
|
+
_MCP_EXTRA_HEADER = (
|
|
42
|
+
f" google-ads-mcp/{_get_package_version_with_fallback()}"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def _mcp_intercept(self, continuation, client_call_details, request):
|
|
46
|
+
"""Generic interceptor used for Unary-Unary and Unary-Stream requests.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
continuation: a function to continue the request process.
|
|
50
|
+
client_call_details: a grpc._interceptor._ClientCallDetails
|
|
51
|
+
instance containing request metadata.
|
|
52
|
+
request: a SearchGoogleAdsRequest or SearchGoogleAdsStreamRequest
|
|
53
|
+
message class instance.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
A grpc.Call/grpc.Future instance representing a service response.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
if client_call_details.metadata is None:
|
|
60
|
+
metadata = []
|
|
61
|
+
else:
|
|
62
|
+
metadata = list(client_call_details.metadata)
|
|
63
|
+
|
|
64
|
+
for i, metadatum in enumerate(metadata):
|
|
65
|
+
# Check if the user agent header key is in the current metadatum
|
|
66
|
+
if metadatum[0] == self._API_CLIENT_HEADER:
|
|
67
|
+
# Convert the tuple to a list so it can be modified.
|
|
68
|
+
val = list(metadatum)
|
|
69
|
+
# Check that "google-ads-mcp" isn't already included in the user agent.
|
|
70
|
+
if "google-ads-mcp" not in val[1]:
|
|
71
|
+
# Append the protobuf version key value pair to the end of
|
|
72
|
+
# the string.
|
|
73
|
+
val[1] += self._MCP_EXTRA_HEADER
|
|
74
|
+
# Convert the metadatum back to a tuple and
|
|
75
|
+
# Splice it back in its original position in
|
|
76
|
+
# order to preserve the order of the metadata list.
|
|
77
|
+
metadata[i] = tuple(val)
|
|
78
|
+
# Exit the loop since we already found the user agent.
|
|
79
|
+
break
|
|
80
|
+
|
|
81
|
+
new_client_call_details = client_call_details._replace(
|
|
82
|
+
metadata=metadata
|
|
83
|
+
)
|
|
84
|
+
return continuation(new_client_call_details, request)
|
|
85
|
+
except:
|
|
86
|
+
logger.error("Error in MCPHeaderInterceptor", exc_info=True)
|
|
87
|
+
return continuation(client_call_details, request)
|
|
88
|
+
|
|
89
|
+
def intercept_unary_stream(
|
|
90
|
+
self, continuation, client_call_details, request
|
|
91
|
+
):
|
|
92
|
+
return self._mcp_intercept(continuation, client_call_details, request)
|
|
93
|
+
|
|
94
|
+
def intercept_unary_unary(self, continuation, client_call_details, request):
|
|
95
|
+
return self._mcp_intercept(continuation, client_call_details, request)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Entry point for the MCP server."""
|
|
16
|
+
|
|
17
|
+
from ads_mcp.coordinator import mcp
|
|
18
|
+
|
|
19
|
+
# The following imports are necessary to register the tools with the `mcp`
|
|
20
|
+
# object, even though they are not directly used in this file.
|
|
21
|
+
# The `# noqa: F401` comment tells the linter to ignore the "unused import"
|
|
22
|
+
# warning.
|
|
23
|
+
from ads_mcp.tools import search, core # noqa: F401
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def run_server() -> None:
|
|
27
|
+
mcp.run()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
if __name__ == "__main__":
|
|
31
|
+
run_server()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Tools for exposing simple, core API methods to the MCP server."""
|
|
16
|
+
|
|
17
|
+
from typing import List
|
|
18
|
+
from ads_mcp.coordinator import mcp
|
|
19
|
+
|
|
20
|
+
import ads_mcp.utils as utils
|
|
21
|
+
|
|
22
|
+
from google.ads.googleads.v21.services.types.customer_service import (
|
|
23
|
+
ListAccessibleCustomersResponse,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@mcp.tool()
|
|
28
|
+
def list_accessible_customers() -> List[str]:
|
|
29
|
+
"""Returns ids of customers directly accessible by the user authenticating the call."""
|
|
30
|
+
ga_service = utils.get_googleads_service("CustomerService")
|
|
31
|
+
accessible_customers: ListAccessibleCustomersResponse = (
|
|
32
|
+
ga_service.list_accessible_customers()
|
|
33
|
+
)
|
|
34
|
+
# remove customer/ from the start of each resource
|
|
35
|
+
return [
|
|
36
|
+
cust_rn.removeprefix("customers/")
|
|
37
|
+
for cust_rn in accessible_customers.resource_names
|
|
38
|
+
]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Tools for exposing the API Search method to the MCP server."""
|
|
16
|
+
|
|
17
|
+
from typing import Any, Dict, List
|
|
18
|
+
from ads_mcp.coordinator import mcp
|
|
19
|
+
import ads_mcp.utils as utils
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def search(
|
|
23
|
+
customer_id: str,
|
|
24
|
+
fields: List[str],
|
|
25
|
+
resource: str,
|
|
26
|
+
conditions: List[str] = None,
|
|
27
|
+
orderings: List[str] = None,
|
|
28
|
+
limit: int | str = None,
|
|
29
|
+
) -> List[Dict[str, Any]]:
|
|
30
|
+
"""Fetches data from the Google Ads API using the search method
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
customer_id: The id of the customer
|
|
34
|
+
fields: The fields to fetch
|
|
35
|
+
resource: The resource to return fields from
|
|
36
|
+
conditions: List of conditions to filter the data, combined using AND clauses
|
|
37
|
+
orderings: How the data is ordered
|
|
38
|
+
limit: The maximum number of rows to return
|
|
39
|
+
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
ga_service = utils.get_googleads_service("GoogleAdsService")
|
|
43
|
+
|
|
44
|
+
query_parts = [f"SELECT {','.join(fields)} FROM {resource}"]
|
|
45
|
+
|
|
46
|
+
if conditions:
|
|
47
|
+
query_parts.append(f" WHERE {' AND '.join(conditions)}")
|
|
48
|
+
|
|
49
|
+
if orderings:
|
|
50
|
+
query_parts.append(f" ORDER BY {','.join(orderings)}")
|
|
51
|
+
|
|
52
|
+
if limit:
|
|
53
|
+
query_parts.append(f" LIMIT {limit}")
|
|
54
|
+
|
|
55
|
+
query = "".join(query_parts)
|
|
56
|
+
utils.logger.info(f"ads_mcp.search query {query}")
|
|
57
|
+
|
|
58
|
+
query_result = ga_service.search_stream(
|
|
59
|
+
customer_id=customer_id, query=query
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
final_output: List = []
|
|
63
|
+
for batch in query_result:
|
|
64
|
+
for row in batch.results:
|
|
65
|
+
final_output.append(
|
|
66
|
+
utils.format_output_row(row, batch.field_mask.paths)
|
|
67
|
+
)
|
|
68
|
+
return final_output
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _search_tool_description() -> str:
|
|
72
|
+
"""Returns the description for the `search` tool."""
|
|
73
|
+
# Add a warning that will be part of the description
|
|
74
|
+
file_content = (
|
|
75
|
+
"WARNING: The table of selectable fields is missing. "
|
|
76
|
+
"Tool may not function correctly."
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
with open(utils.GAQL_FILEPATH, "r") as file:
|
|
81
|
+
file_content = file.read()
|
|
82
|
+
except FileNotFoundError:
|
|
83
|
+
utils.logger.error("The specified file was not found.")
|
|
84
|
+
|
|
85
|
+
return f"""
|
|
86
|
+
{search.__doc__}
|
|
87
|
+
|
|
88
|
+
### Hints
|
|
89
|
+
Language Grammar can be found at https://developers.google.com/google-ads/api/docs/query/grammar
|
|
90
|
+
All resources and descriptions are found at https://developers.google.com/google-ads/api/fields/v21/overview
|
|
91
|
+
|
|
92
|
+
For Conversion issues try looking in offline_conversion_upload_conversion_action_summary
|
|
93
|
+
|
|
94
|
+
### Hint for customer_id
|
|
95
|
+
should be a string of numbers without punctuation
|
|
96
|
+
if presented in the form 123-456-7890 remove the hyphens and use 1234567890
|
|
97
|
+
|
|
98
|
+
### Hints for Dates
|
|
99
|
+
All dates should be in the form YYYY-MM-DD and must include the dashes (-)
|
|
100
|
+
Date literals from the Grammar must NEVER be used
|
|
101
|
+
Date ranges should be finite and must include a start and end date
|
|
102
|
+
|
|
103
|
+
### Hints for limits
|
|
104
|
+
Requests to resource change_event must specify a LIMIT of less than or equal to 10000
|
|
105
|
+
|
|
106
|
+
### Hints for conversions questions
|
|
107
|
+
https://developers.google.com/google-ads/api/docs/conversions/upload-summaries
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
### Hints for all fields
|
|
111
|
+
What follows is a table of resources and their selectable fields (fields), filterable fields (used in the condition) and sortable fields (use in the ordering)
|
|
112
|
+
Fields are comma separated, the whole field must be used, wildcards and partial fields are not allowed
|
|
113
|
+
All fields must come from this table and be prefixed with the resource being searched
|
|
114
|
+
{file_content}
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# The `search` tool requires a more complex description that's generated at
|
|
119
|
+
# runtime. Uses the `add_tool` method instead of an annnotation since `add_tool`
|
|
120
|
+
# provides the flexibility needed to generate the description while also
|
|
121
|
+
# including the `search` method's docstring.
|
|
122
|
+
mcp.add_tool(
|
|
123
|
+
search,
|
|
124
|
+
title="Fetches data from the Google Ads API using the search method",
|
|
125
|
+
description=_search_tool_description(),
|
|
126
|
+
)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Tools for generating file containing a list of resources and their fields."""
|
|
16
|
+
|
|
17
|
+
import utils
|
|
18
|
+
import json
|
|
19
|
+
import collections
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def update_gaql_resource_file():
|
|
23
|
+
"""Fetches all Google Ads fields and their attributes, groups them by resource, and saves to a JSON file."""
|
|
24
|
+
|
|
25
|
+
ga_service = utils.get_googleads_service("GoogleAdsFieldService")
|
|
26
|
+
|
|
27
|
+
request = utils.get_googleads_type("SearchGoogleAdsFieldsRequest")
|
|
28
|
+
|
|
29
|
+
# Query to select the name and key attributes for ALL fields.
|
|
30
|
+
# We no longer filter by category = 'RESOURCE' here, as we need attributes
|
|
31
|
+
# for all fields associated with resources.
|
|
32
|
+
query = "SELECT name, selectable, filterable, sortable"
|
|
33
|
+
request.query = query
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
response = ga_service.search_google_ads_fields(request=request)
|
|
37
|
+
except Exception as e:
|
|
38
|
+
raise RuntimeError(f"API call to search_google_ads_fields failed: {e}")
|
|
39
|
+
|
|
40
|
+
if response.total_results_count == 0:
|
|
41
|
+
print("No GoogleAdsFields found.")
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
# Dictionary to store the grouped results
|
|
45
|
+
# Example: {'campaign': {'selectable': [], 'filterable': [], 'sortable': []}, ...}
|
|
46
|
+
resource_data = collections.defaultdict(
|
|
47
|
+
lambda: {"selectable": [], "filterable": [], "sortable": []}
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
for googleads_field in response:
|
|
51
|
+
field_name = googleads_field.name
|
|
52
|
+
# Extract the base resource name (e.g., 'campaign' from 'campaign.id')
|
|
53
|
+
if "." in field_name:
|
|
54
|
+
resource_name = field_name.split(".")[0]
|
|
55
|
+
|
|
56
|
+
if googleads_field.selectable:
|
|
57
|
+
resource_data[resource_name]["selectable"].append(field_name)
|
|
58
|
+
if googleads_field.filterable:
|
|
59
|
+
resource_data[resource_name]["filterable"].append(field_name)
|
|
60
|
+
if googleads_field.sortable:
|
|
61
|
+
resource_data[resource_name]["sortable"].append(field_name)
|
|
62
|
+
# We can ignore fields that don't contain a '.' as they are likely
|
|
63
|
+
# top-level resources themselves and don't have these attributes in the same way.
|
|
64
|
+
|
|
65
|
+
# Prepare the final output structure
|
|
66
|
+
output_list = []
|
|
67
|
+
for resource, attributes in resource_data.items():
|
|
68
|
+
output_list.append(
|
|
69
|
+
{
|
|
70
|
+
"resource": resource,
|
|
71
|
+
"selectable": sorted(attributes["selectable"]),
|
|
72
|
+
"filterable": sorted(attributes["filterable"]),
|
|
73
|
+
"sortable": sorted(attributes["sortable"]),
|
|
74
|
+
}
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# Sort the list of resources for consistent output
|
|
78
|
+
output_list.sort(key=lambda x: x["resource"])
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
with open(utils.GAQL_FILEPATH, "w") as file:
|
|
82
|
+
json.dump(output_list, file, indent=4)
|
|
83
|
+
print(f"Successfully updated resource file: {utils.GAQL_FILEPATH}")
|
|
84
|
+
except IOError as e:
|
|
85
|
+
raise RuntimeError(
|
|
86
|
+
f"Failed to write to file {utils.GAQL_FILEPATH}: {e}"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if __name__ == "__main__":
|
|
91
|
+
update_gaql_resource_file()
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
# Copyright 2025 Google LLC.
|
|
4
|
+
#
|
|
5
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# you may not use this file except in compliance with the License.
|
|
7
|
+
# You may obtain a copy of the License at
|
|
8
|
+
#
|
|
9
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
#
|
|
11
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# See the License for the specific language governing permissions and
|
|
15
|
+
# limitations under the License.
|
|
16
|
+
|
|
17
|
+
"""Common utilities used by the MCP server."""
|
|
18
|
+
|
|
19
|
+
from typing import Any
|
|
20
|
+
import proto
|
|
21
|
+
import logging
|
|
22
|
+
import json
|
|
23
|
+
from google.ads.googleads.client import GoogleAdsClient
|
|
24
|
+
from google.ads.googleads.v21.services.services.google_ads_service import (
|
|
25
|
+
GoogleAdsServiceClient,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
from google.ads.googleads.util import get_nested_attr
|
|
29
|
+
import google.auth
|
|
30
|
+
from google.oauth2 import service_account
|
|
31
|
+
from ads_mcp.mcp_header_interceptor import MCPHeaderInterceptor
|
|
32
|
+
import os
|
|
33
|
+
|
|
34
|
+
GAQL_FILEPATH = "ads_mcp/gaql_resources.txt"
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
logging.basicConfig(level=logging.INFO)
|
|
38
|
+
|
|
39
|
+
# Read-only scope for Analytics Admin API and Analytics Data API.
|
|
40
|
+
_READ_ONLY_ADS_SCOPE = "https://www.googleapis.com/auth/adwords"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _get_subject() -> str:
|
|
44
|
+
"""Returns the subject for impersonation from the environment variable GOOGLE_ADS_SUBJECT."""
|
|
45
|
+
return os.environ.get("GOOGLE_ADS_SUBJECT")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _create_credentials() -> google.auth.credentials.Credentials:
|
|
49
|
+
"""Returns credentials with optional subject delegation support."""
|
|
50
|
+
subject = _get_subject()
|
|
51
|
+
credentials_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
|
|
52
|
+
|
|
53
|
+
if subject and credentials_path:
|
|
54
|
+
logger.info(f"Subject specified: {subject}")
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
# Check if it's a service account file
|
|
58
|
+
with open(credentials_path, 'r') as f:
|
|
59
|
+
creds_info = json.load(f)
|
|
60
|
+
|
|
61
|
+
if creds_info.get('type') == 'service_account':
|
|
62
|
+
logger.info("Using service account with subject delegation")
|
|
63
|
+
# Service account credentials with subject delegation
|
|
64
|
+
credentials = service_account.Credentials.from_service_account_file(
|
|
65
|
+
credentials_path,
|
|
66
|
+
scopes=[_READ_ONLY_ADS_SCOPE]
|
|
67
|
+
)
|
|
68
|
+
# Apply subject delegation
|
|
69
|
+
delegated_credentials = credentials.with_subject(subject)
|
|
70
|
+
logger.info(f"Successfully applied subject delegation for: {subject}")
|
|
71
|
+
return delegated_credentials
|
|
72
|
+
else:
|
|
73
|
+
# OAuth credentials - subject parameter is logged but ignored
|
|
74
|
+
logger.info(f"Subject '{subject}' specified but using OAuth credentials. Subject delegation requires service account credentials. Proceeding with OAuth.")
|
|
75
|
+
|
|
76
|
+
except Exception as e:
|
|
77
|
+
logger.warning(f"Error processing credentials file for subject delegation: {e}. Falling back to default authentication.")
|
|
78
|
+
|
|
79
|
+
# Default behavior: no subject or fallback
|
|
80
|
+
if subject:
|
|
81
|
+
logger.info("Using default authentication (subject parameter ignored)")
|
|
82
|
+
else:
|
|
83
|
+
logger.info("Using default authentication (no subject specified)")
|
|
84
|
+
|
|
85
|
+
(credentials, _) = google.auth.default(scopes=[_READ_ONLY_ADS_SCOPE])
|
|
86
|
+
return credentials
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _get_developer_token() -> str:
|
|
90
|
+
"""Returns the developer token from the environment variable GOOGLE_ADS_DEVELOPER_TOKEN."""
|
|
91
|
+
dev_token = os.environ.get("GOOGLE_ADS_DEVELOPER_TOKEN")
|
|
92
|
+
if dev_token is None:
|
|
93
|
+
raise ValueError(
|
|
94
|
+
"GOOGLE_ADS_DEVELOPER_TOKEN environment variable not set."
|
|
95
|
+
)
|
|
96
|
+
return dev_token
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _get_login_customer_id() -> str:
|
|
100
|
+
"""Returns login customer id, if set, from the environment variable GOOGLE_ADS_LOGIN_CUSTOMER_ID."""
|
|
101
|
+
return os.environ.get("GOOGLE_ADS_LOGIN_CUSTOMER_ID")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _get_googleads_client() -> GoogleAdsClient:
|
|
105
|
+
# Use this line if you have a google-ads.yaml file
|
|
106
|
+
# client = GoogleAdsClient.load_from_storage()
|
|
107
|
+
client = GoogleAdsClient(
|
|
108
|
+
credentials=_create_credentials(),
|
|
109
|
+
developer_token=_get_developer_token(),
|
|
110
|
+
login_customer_id=_get_login_customer_id()
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
return client
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
_googleads_client = _get_googleads_client()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get_googleads_service(serviceName: str) -> GoogleAdsServiceClient:
|
|
120
|
+
return _googleads_client.get_service(
|
|
121
|
+
serviceName, interceptors=[MCPHeaderInterceptor()]
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def get_googleads_type(typeName: str):
|
|
126
|
+
return _googleads_client.get_type(typeName)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def format_output_value(value: Any) -> Any:
|
|
130
|
+
if isinstance(value, proto.Enum):
|
|
131
|
+
return value.name
|
|
132
|
+
else:
|
|
133
|
+
return value
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def format_output_row(row: proto.Message, attributes):
|
|
137
|
+
return {
|
|
138
|
+
attr: format_output_value(get_nested_attr(row, attr))
|
|
139
|
+
for attr in attributes
|
|
140
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: google-ads-mcp-python
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
License-Expression: Apache-2.0
|
|
5
|
+
Requires-Dist: google-ads>=28.0.0
|
|
6
|
+
Requires-Dist: mcp[cli]>=1.2.0
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Project-URL: homepage, https://github.com/locomotive-agency/google-ads-mcp
|
|
9
|
+
Project-URL: issues, https://github.com/locomotive-agency/google-ads-mcp/issues
|
|
10
|
+
Project-URL: repository, https://github.com/locomotive-agency/google-ads-mcp.git
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
google_ads_mcp_python/__init__.py,sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855,0
|
|
2
|
+
google_ads_mcp_python/coordinator.py,sha256=57369e026831ec5073494516792b0f497e39367708df5287538d80814ea28aea,876
|
|
3
|
+
google_ads_mcp_python/gaql_resources.txt,sha256=9d674ce3fd5a60e9e8cea563dae7fa322e95df5fb5a02a5c624dc3c67664e2c2,394275
|
|
4
|
+
google_ads_mcp_python/mcp_header_interceptor.py,sha256=9edf44c9c555a53ddfede9865185801057855a018fb43f2025b7b71476bf9fa2,3751
|
|
5
|
+
google_ads_mcp_python/server.py,sha256=c690f463a959dab19f9ea5d84a988062d7842e087fc9fcb3ac69054edcbe5497,1019
|
|
6
|
+
google_ads_mcp_python/tools/core.py,sha256=8ea0b4aa79e53b72e1af2281d78b43e01e87284ea48ed56bbb9e34272ae8d433,1356
|
|
7
|
+
google_ads_mcp_python/tools/search.py,sha256=f106b706401eba5db81dbcfe4500eb9e51add46d5642dfad0ccd9b4ca1ae35e8,4416
|
|
8
|
+
google_ads_mcp_python/update_references.py,sha256=efc8b0d9c35fdd7118f57ab2442c770fed7d3308d68a73bff9a9d4d1877d0721,3481
|
|
9
|
+
google_ads_mcp_python/utils.py,sha256=90936a52944b4a1fd21975594d4264666f5d5a9a462b38f25bfe1f2a13d519a8,4967
|
|
10
|
+
google_ads_mcp_python-0.1.0.dist-info/WHEEL,sha256=76443c98c0efcfdd1191eac5fa1d8223dba1c474dbd47676674a255e7ca48770,79
|
|
11
|
+
google_ads_mcp_python-0.1.0.dist-info/entry_points.txt,sha256=0f6544671aeee83474759faccb945ad19ea49db6db427ae74bcb9231aba87b4f,143
|
|
12
|
+
google_ads_mcp_python-0.1.0.dist-info/METADATA,sha256=d1e288bbad8fc936a93389140accf14004a3d8dbddb8dc64038ddd57f626fff6,421
|
|
13
|
+
google_ads_mcp_python-0.1.0.dist-info/RECORD,,
|