forked from Jang-myoung-gyoon/google-play-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1937 lines (1561 loc) · 65 KB
/
server.py
File metadata and controls
1937 lines (1561 loc) · 65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Google Play Developer API MCP Server.
Provides tools for managing Google Play app deployment, store listings,
in-app products, and subscriptions.
Deployment:
- deploy_internal: Upload AAB and deploy to internal testing track
- deploy_track: Upload AAB and deploy to any track
- deploy_production: Upload AAB and deploy to production (requires confirmation)
- get_app_info: Get app track information
Store Listing:
- get_store_listing: Get current store listing
- update_store_listing: Update store listing text
- upload_store_image: Upload a single image
- batch_upload_store_images: Upload all images from a directory
- list_store_images: List uploaded images
- delete_store_image: Delete a single image
- delete_all_store_images: Delete all images of a given type
In-App Products:
- create_inapp_product: Create or update a one-time product
- activate_inapp_product: Activate a draft product
- deactivate_inapp_product: Deactivate a product
- list_inapp_products: List all one-time products
- batch_create_inapp_products: Create multiple products at once
- batch_activate_inapp_products: Activate multiple products at once
Subscriptions:
- list_subscriptions: List all subscriptions
- create_subscription: Create a subscription with base plans
- update_subscription: Update subscription listings
- delete_subscription: Delete a subscription
- activate_base_plan: Activate a draft base plan
- deactivate_base_plan: Deactivate a base plan
- create_free_trial_offer: Create a free trial offer
- activate_offer: Activate a draft offer
- deactivate_offer: Deactivate an offer
"""
import json
import os
from decimal import Decimal
from pathlib import Path
from dotenv import load_dotenv
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from mcp.server.fastmcp import FastMCP
load_dotenv(Path(__file__).parent / ".env")
mcp = FastMCP("google-play")
SCOPES = ["https://www.googleapis.com/auth/androidpublisher"]
# ---------------------------------------------------------------------------
# Core helpers
# ---------------------------------------------------------------------------
def _get_service():
"""Create Google Play Developer API service from environment variables."""
key_file = os.environ.get("GOOGLE_PLAY_KEY_FILE")
if not key_file:
raise ValueError(
"GOOGLE_PLAY_KEY_FILE environment variable is not set. "
"Please set it to the path of your service account JSON key file."
)
if not os.path.exists(key_file):
raise ValueError(f"Service account key file not found: {key_file}")
credentials = service_account.Credentials.from_service_account_file(
key_file, scopes=SCOPES
)
return build("androidpublisher", "v3", credentials=credentials)
def _get_package_name() -> str:
"""Get the package name from environment variable."""
package_name = os.environ.get("GOOGLE_PLAY_PACKAGE_NAME")
if not package_name:
raise ValueError(
"GOOGLE_PLAY_PACKAGE_NAME environment variable is not set. "
"Please set it to your app's package name (e.g., com.example.app)."
)
return package_name
# ---------------------------------------------------------------------------
# Pricing helpers
# ---------------------------------------------------------------------------
# Google Play regional price caps (whole currency units).
# The API rejects prices above these. Add more as discovered from API errors.
_REGION_MAX_PRICE_UNITS = {
"KR": 570_000, # KRW ₩570,000
"CL": 350_000, # CLP 350,000
"VN": 12_500_000, # VND ₫12,500,000
}
# Map currency codes to their primary region code (for price verification).
_CURRENCY_TO_REGION = {
"RON": "RO", "EUR": "DE", "USD": "US", "TRY": "TR", "GBP": "GB",
"PHP": "PH", "INR": "IN", "ARS": "AR", "BRL": "BR", "JPY": "JP",
"KRW": "KR", "PLN": "PL", "CZK": "CZ", "HUF": "HU", "SEK": "SE",
"NOK": "NO", "DKK": "DK", "CHF": "CH", "CAD": "CA", "AUD": "AU",
"MXN": "MX", "CLP": "CL", "COP": "CO", "PEN": "PE", "EGP": "EG",
"ZAR": "ZA", "NGN": "NG", "SAR": "SA", "AED": "AE", "ILS": "IL",
"TWD": "TW", "HKD": "HK", "SGD": "SG", "MYR": "MY", "THB": "TH",
"IDR": "ID", "VND": "VN", "UAH": "UA", "BGN": "BG", "HRK": "HR",
}
# US age rating tiers for in-app products and subscriptions.
_AGE_RATING_MAP = {
"EVERYONE": "PRODUCT_AGE_RATING_TIER_EVERYONE",
"13+": "PRODUCT_AGE_RATING_TIER_THIRTEEN_AND_ABOVE",
"16+": "PRODUCT_AGE_RATING_TIER_SIXTEEN_AND_ABOVE",
"18+": "PRODUCT_AGE_RATING_TIER_EIGHTEEN_AND_ABOVE",
}
def _age_rating_settings(age_rating: str) -> dict:
"""Build taxAndComplianceSettings with US age rating."""
tier = _AGE_RATING_MAP.get(age_rating, _AGE_RATING_MAP["EVERYONE"])
return {
"regionalProductAgeRatingInfos": [
{"regionCode": "US", "productAgeRatingTier": tier},
],
}
def _price_to_units_nanos(price: float) -> tuple[int, int]:
"""Convert a decimal price to (units, nanos) using Decimal for precision."""
d = Decimal(str(price))
units = int(d)
nanos = int((d - units) * 1_000_000_000)
return units, nanos
def _format_money(price_obj: dict) -> str:
"""Format a Google Money object as a human-readable string."""
if not price_obj:
return "N/A"
units = int(price_obj.get("units", "0"))
nanos = price_obj.get("nanos", 0)
currency = price_obj.get("currencyCode", "???")
if nanos == 0:
return f"{units:,} {currency}"
value = units + nanos / 1_000_000_000
return f"{value:,.2f} {currency}"
def _cap_price(region_code: str, units: int, nanos: int) -> tuple[int, int, bool]:
"""Cap price at regional maximum if exceeded. Returns (units, nanos, was_capped)."""
max_units = _REGION_MAX_PRICE_UNITS.get(region_code)
if max_units is not None and units > max_units:
return max_units, 0, True
return units, nanos, False
def _convert_prices(service, package_name: str, price: float, currency_code: str) -> dict:
"""Convert a price to all regions via the Google Play API.
Returns dict with 'regionsVersion' and 'convertedRegionPrices'.
"""
units, nanos = _price_to_units_nanos(price)
result = service.monetization().convertRegionPrices(
packageName=package_name,
body={
"price": {
"currencyCode": currency_code,
"units": str(units),
"nanos": nanos,
}
},
).execute()
return {
"regionsVersion": result["regionVersion"]["version"],
"convertedRegionPrices": result.get("convertedRegionPrices", {}),
}
def _build_regional_configs(converted_prices: dict) -> tuple[list, list[str]]:
"""Build one-time product regional pricing configs with capping.
Returns (regional_configs, cap_warnings).
"""
regional_configs = []
cap_warnings = []
seen_regions = set()
for region_code, price_data in converted_prices.items():
if region_code in seen_regions:
continue
seen_regions.add(region_code)
p = price_data["price"]
units = int(p.get("units", "0"))
nanos = p.get("nanos", 0)
units, nanos, was_capped = _cap_price(region_code, units, nanos)
if was_capped:
cap_warnings.append(
f" {region_code}: capped to {units:,} {p['currencyCode']} "
f"(limit: {_REGION_MAX_PRICE_UNITS[region_code]:,})"
)
regional_configs.append({
"regionCode": region_code,
"price": {
"currencyCode": p["currencyCode"],
"units": str(units),
"nanos": nanos,
},
"availability": "AVAILABLE",
})
return regional_configs, cap_warnings
def _build_subscription_regional_configs(converted_prices: dict) -> tuple[list, list[str]]:
"""Build subscription regional pricing configs with capping.
Returns (regional_configs, cap_warnings).
"""
regional_configs = []
cap_warnings = []
seen_regions = set()
for region_code, price_data in converted_prices.items():
if region_code in seen_regions:
continue
seen_regions.add(region_code)
p = price_data["price"]
units = int(p.get("units", "0"))
nanos = p.get("nanos", 0)
units, nanos, was_capped = _cap_price(region_code, units, nanos)
if was_capped:
cap_warnings.append(
f" {region_code}: capped to {units:,} {p['currencyCode']} "
f"(limit: {_REGION_MAX_PRICE_UNITS[region_code]:,})"
)
regional_configs.append({
"regionCode": region_code,
"newSubscriberAvailability": True,
"price": {
"currencyCode": p["currencyCode"],
"units": str(units),
"nanos": nanos,
},
})
return regional_configs, cap_warnings
def _extract_verification_prices(result: dict, target_region: str | None) -> str:
"""Extract key prices from one-time product API result for verification."""
lines = []
for opt in result.get("purchaseOptions", []):
for cfg in opt.get("regionalPricingAndAvailabilityConfigs", []):
region = cfg.get("regionCode", "")
price_str = _format_money(cfg.get("price", {}))
if region == target_region:
lines.insert(0, f" {region} (target): {price_str}")
elif region == "US":
lines.append(f" US: {price_str}")
elif region == "DE":
lines.append(f" DE (EUR): {price_str}")
return "\n".join(lines[:5])
def _extract_subscription_verification(result: dict, target_region: str | None) -> str:
"""Extract key prices from subscription API result for verification."""
lines = []
for plan in result.get("basePlans", []):
plan_id = plan.get("basePlanId", "?")
for cfg in plan.get("regionalConfigs", []):
region = cfg.get("regionCode", "")
price_str = _format_money(cfg.get("price", {}))
if region == target_region:
lines.append(f" {plan_id} / {region} (target): {price_str}")
elif region == "US":
lines.append(f" {plan_id} / US: {price_str}")
return "\n".join(lines[:10])
# ---------------------------------------------------------------------------
# Edit helpers (for deployment/store listing)
# ---------------------------------------------------------------------------
def _commit_edit(service, package_name: str, edit_id: str):
"""Commit an edit, handling draft apps that require a track update."""
track = service.edits().tracks().get(
packageName=package_name,
editId=edit_id,
track="internal",
).execute()
releases = track.get("releases", [])
if releases:
latest = releases[0]
latest["status"] = "draft"
releases = [latest]
else:
releases = [{"status": "draft"}]
service.edits().tracks().update(
packageName=package_name,
editId=edit_id,
track="internal",
body={"track": "internal", "releases": releases},
).execute()
service.edits().commit(packageName=package_name, editId=edit_id).execute()
# ---------------------------------------------------------------------------
# Deployment tools
# ---------------------------------------------------------------------------
@mcp.tool()
def deploy_internal(
aab_path: str,
release_notes_en: str = "",
release_notes_ko: str = "",
status: str = "draft",
) -> str:
"""Deploy an Android App Bundle to the internal testing track.
Args:
aab_path: Path to the .aab file to upload.
release_notes_en: Release notes in English (optional).
release_notes_ko: Release notes in Korean (optional).
status: Release status - "draft" for unpublished apps, "completed" for
published apps. Default is "draft".
Returns:
A message indicating success with version code and edit ID.
"""
service = _get_service()
package_name = _get_package_name()
if not os.path.exists(aab_path):
raise ValueError(f"AAB file not found: {aab_path}")
edit = service.edits().insert(packageName=package_name, body={}).execute()
edit_id = edit["id"]
try:
media = MediaFileUpload(aab_path, mimetype="application/octet-stream")
bundle = service.edits().bundles().upload(
packageName=package_name,
editId=edit_id,
media_body=media,
).execute()
version_code = bundle["versionCode"]
release_notes = []
if release_notes_en:
release_notes.append({"language": "en-US", "text": release_notes_en})
if release_notes_ko:
release_notes.append({"language": "ko-KR", "text": release_notes_ko})
track_body = {
"track": "internal",
"releases": [{
"versionCodes": [str(version_code)],
"status": status,
}],
}
if release_notes:
track_body["releases"][0]["releaseNotes"] = release_notes
service.edits().tracks().update(
packageName=package_name,
editId=edit_id,
track="internal",
body=track_body,
).execute()
service.edits().commit(packageName=package_name, editId=edit_id).execute()
return (
f"Successfully deployed to internal testing track.\n"
f"Version code: {version_code}\n"
f"Status: {status}\n"
f"Edit ID: {edit_id}"
)
except Exception as e:
try:
service.edits().delete(packageName=package_name, editId=edit_id).execute()
except Exception:
pass
raise e
@mcp.tool()
def deploy_track(
aab_path: str,
track: str = "internal",
release_notes_en: str = "",
release_notes_ko: str = "",
status: str = "draft",
) -> str:
"""Deploy an Android App Bundle to any testing track.
Args:
aab_path: Path to the .aab file to upload.
track: Target track - "internal", "alpha", "beta", or "production".
release_notes_en: Release notes in English (optional).
release_notes_ko: Release notes in Korean (optional).
status: Release status - "draft" or "completed". Default is "draft".
Returns:
A message indicating success with version code and edit ID.
"""
valid_tracks = ("internal", "alpha", "beta", "production")
if track not in valid_tracks:
raise ValueError(f"Invalid track: {track}. Must be one of {valid_tracks}")
service = _get_service()
package_name = _get_package_name()
if not os.path.exists(aab_path):
raise ValueError(f"AAB file not found: {aab_path}")
track_display = {
"internal": "internal testing",
"alpha": "closed testing",
"beta": "open testing",
"production": "production",
}
edit = service.edits().insert(packageName=package_name, body={}).execute()
edit_id = edit["id"]
try:
media = MediaFileUpload(aab_path, mimetype="application/octet-stream")
bundle = service.edits().bundles().upload(
packageName=package_name,
editId=edit_id,
media_body=media,
).execute()
version_code = bundle["versionCode"]
release_notes = []
if release_notes_en:
release_notes.append({"language": "en-US", "text": release_notes_en})
if release_notes_ko:
release_notes.append({"language": "ko-KR", "text": release_notes_ko})
track_body = {
"track": track,
"releases": [{
"versionCodes": [str(version_code)],
"status": status,
}],
}
if release_notes:
track_body["releases"][0]["releaseNotes"] = release_notes
service.edits().tracks().update(
packageName=package_name,
editId=edit_id,
track=track,
body=track_body,
).execute()
service.edits().commit(packageName=package_name, editId=edit_id).execute()
return (
f"Successfully deployed to {track_display[track]} track.\n"
f"Version code: {version_code}\n"
f"Status: {status}\n"
f"Edit ID: {edit_id}"
)
except Exception as e:
try:
service.edits().delete(packageName=package_name, editId=edit_id).execute()
except Exception:
pass
raise e
@mcp.tool()
def deploy_production(
aab_path: str,
release_notes_en: str = "",
release_notes_ko: str = "",
status: str = "completed",
) -> str:
"""Deploy an Android App Bundle to the PRODUCTION track.
CRITICAL: You MUST ask for explicit user confirmation before calling this.
Production deployment publishes the app to ALL users on Google Play.
Args:
aab_path: Path to the .aab file to upload.
release_notes_en: Release notes in English (optional).
release_notes_ko: Release notes in Korean (optional).
status: Release status - "completed", "halted", or "inProgress".
Returns:
A message indicating success with version code and edit ID.
"""
service = _get_service()
package_name = _get_package_name()
if not os.path.exists(aab_path):
raise ValueError(f"AAB file not found: {aab_path}")
edit = service.edits().insert(packageName=package_name, body={}).execute()
edit_id = edit["id"]
try:
media = MediaFileUpload(aab_path, mimetype="application/octet-stream")
bundle = service.edits().bundles().upload(
packageName=package_name,
editId=edit_id,
media_body=media,
).execute()
version_code = bundle["versionCode"]
release_notes = []
if release_notes_en:
release_notes.append({"language": "en-US", "text": release_notes_en})
if release_notes_ko:
release_notes.append({"language": "ko-KR", "text": release_notes_ko})
release = {
"versionCodes": [str(version_code)],
"status": status,
}
if release_notes:
release["releaseNotes"] = release_notes
track_body = {
"track": "production",
"releases": [release],
}
service.edits().tracks().update(
packageName=package_name,
editId=edit_id,
track="production",
body=track_body,
).execute()
service.edits().commit(packageName=package_name, editId=edit_id).execute()
return (
f"Successfully deployed to PRODUCTION track.\n"
f"Version code: {version_code}\n"
f"Status: {status}\n"
f"Edit ID: {edit_id}"
)
except Exception as e:
try:
service.edits().delete(packageName=package_name, editId=edit_id).execute()
except Exception:
pass
raise e
@mcp.tool()
def get_app_info() -> str:
"""Get basic app information from Google Play.
Returns:
App details including current version and track information.
"""
service = _get_service()
package_name = _get_package_name()
edit = service.edits().insert(packageName=package_name, body={}).execute()
edit_id = edit["id"]
try:
tracks_result = service.edits().tracks().list(
packageName=package_name,
editId=edit_id,
).execute()
output = [f"Package: {package_name}\n", "Tracks:"]
for track in tracks_result.get("tracks", []):
track_name = track.get("track", "unknown")
releases = track.get("releases", [])
if releases:
latest = releases[0]
version_codes = latest.get("versionCodes", [])
status = latest.get("status", "unknown")
output.append(
f" - {track_name}: version {version_codes}, status: {status}"
)
else:
output.append(f" - {track_name}: no releases")
return "\n".join(output)
finally:
try:
service.edits().delete(packageName=package_name, editId=edit_id).execute()
except Exception:
pass
# ---------------------------------------------------------------------------
# One-time products
# ---------------------------------------------------------------------------
@mcp.tool()
def create_inapp_product(
sku: str,
localizations: str,
price: float,
currency_code: str = "USD",
purchase_option_id: str = "default",
age_rating: str = "EVERYONE",
) -> str:
"""Create or update a one-time in-app product.
Sets explicit regional prices for ALL regions (170+), with automatic
capping for regions with price limits (e.g., KR max 570,000 KRW).
Does NOT use newRegionsConfig to avoid derived-price validation issues.
The price is the BUYER-FACING price (what the customer pays, including tax).
This is the same price you would enter in the Google Play Console.
The target region (determined from currency_code) gets this exact price;
all other regions get Google's exchange-rate-converted equivalents.
IMPORTANT: The app must have BILLING permission and Play Billing Library
in an uploaded bundle before products can be created.
Args:
sku: Product ID (e.g., "rezi_until_exam"). Only lowercase, numbers, underscores.
localizations: JSON array of localizations. Each entry needs "language", "title", "description".
Example: [{"language": "en-US", "title": "Rezi - Until Exam", "description": "Full access"},
{"language": "ro", "title": "Rezidentiat", "description": "Acces complet"}]
price: Buyer-facing price in the specified currency (e.g., 1998 for 1998 RON).
This is what the customer pays (same as Google Play Console).
currency_code: ISO currency code (e.g., "RON", "USD", "EUR", "TRY"). Default "USD".
purchase_option_id: Purchase option ID. Default "default".
age_rating: US age rating. One of "EVERYONE", "13+", "16+", "18+". Default "EVERYONE".
Returns:
Product details including key regional prices for verification.
"""
service = _get_service()
package_name = _get_package_name()
# Convert to all regional prices
info = _convert_prices(service, package_name, price, currency_code)
regions_version = info["regionsVersion"]
# Build explicit per-region configs with capping
regional_configs, cap_warnings = _build_regional_configs(info["convertedRegionPrices"])
# Override the target region with the exact user-specified price
target_region = _CURRENCY_TO_REGION.get(currency_code)
if target_region:
exact_units, exact_nanos = _price_to_units_nanos(price)
for cfg in regional_configs:
if cfg["regionCode"] == target_region:
cfg["price"] = {
"currencyCode": currency_code,
"units": str(exact_units),
"nanos": exact_nanos,
}
break
# Parse localizations
locales = json.loads(localizations)
listings = [
{"languageCode": loc["language"], "title": loc["title"], "description": loc["description"]}
for loc in locales
]
body = {
"packageName": package_name,
"productId": sku,
"listings": listings,
"taxAndComplianceSettings": _age_rating_settings(age_rating),
"purchaseOptions": [{
"purchaseOptionId": purchase_option_id,
"buyOption": {"legacyCompatible": True},
"regionalPricingAndAvailabilityConfigs": regional_configs,
# No newRegionsConfig — all regions have explicit prices.
# New regions Google adds later won't auto-get this product.
}],
}
request = service.monetization().onetimeproducts().patch(
packageName=package_name,
productId=sku,
body=body,
allowMissing=True,
updateMask="listings,purchaseOptions,taxAndComplianceSettings",
)
# Add regionsVersion parameter
sep = "&" if "?" in request.uri else "?"
request.uri += f"{sep}regionsVersion.version={regions_version}"
result = request.execute()
# Build verification output
target_region = _CURRENCY_TO_REGION.get(currency_code)
price_verification = _extract_verification_prices(result, target_region)
output = [
f"Successfully created/updated one-time product: {sku}",
f"Base price: {price:,.2f} {currency_code}",
f"Localizations: {len(listings)}",
f"Regions: {len(regional_configs)}",
]
if cap_warnings:
output.append(f"Price caps applied ({len(cap_warnings)}):")
output.extend(cap_warnings)
if price_verification:
output.append("Verification prices:")
output.append(price_verification)
output.append("Status: DRAFT — use activate_inapp_product to activate.")
return "\n".join(output)
@mcp.tool()
def activate_inapp_product(sku: str, purchase_option_id: str = "default") -> str:
"""Activate a draft in-app product to make it available for purchase.
Args:
sku: Product ID to activate (e.g., "rezi_until_exam").
purchase_option_id: Purchase option ID. Default "default".
Returns:
A message indicating success.
"""
service = _get_service()
package_name = _get_package_name()
service.monetization().onetimeproducts().purchaseOptions().batchUpdateStates(
packageName=package_name,
productId=sku,
body={
"requests": [{
"activatePurchaseOptionRequest": {
"packageName": package_name,
"productId": sku,
"purchaseOptionId": purchase_option_id,
}
}]
},
).execute()
return f"Successfully activated in-app product: {sku}"
@mcp.tool()
def deactivate_inapp_product(sku: str, purchase_option_id: str = "default") -> str:
"""Deactivate an active in-app product.
Args:
sku: Product ID to deactivate (e.g., "rezi_until_exam").
purchase_option_id: Purchase option ID. Default "default".
Returns:
A message indicating success.
"""
service = _get_service()
package_name = _get_package_name()
service.monetization().onetimeproducts().purchaseOptions().batchUpdateStates(
packageName=package_name,
productId=sku,
body={
"requests": [{
"deactivatePurchaseOptionRequest": {
"packageName": package_name,
"productId": sku,
"purchaseOptionId": purchase_option_id,
}
}]
},
).execute()
return f"Successfully deactivated in-app product: {sku}"
@mcp.tool()
def list_inapp_products() -> str:
"""List all one-time in-app products for the app.
Returns:
List of all in-app products with their details.
"""
service = _get_service()
package_name = _get_package_name()
result = service.monetization().onetimeproducts().list(
packageName=package_name,
).execute()
products = result.get("oneTimeProducts", [])
if not products:
return "No in-app products found."
output = [f"Found {len(products)} in-app product(s):\n"]
for product in products:
product_id = product.get("productId", "unknown")
listings = product.get("listings", [])
title = "No title"
for listing in listings:
if listing.get("languageCode") == "en-US":
title = listing.get("title", title)
break
if title == "No title" and listings:
title = listings[0].get("title", title)
options = product.get("purchaseOptions", [])
status = "UNKNOWN"
price_info = ""
for opt in options:
if "state" in opt:
status = opt["state"]
configs = opt.get("regionalPricingAndAvailabilityConfigs", [])
for cfg in configs:
if cfg.get("regionCode") == "US":
price_info = _format_money(cfg.get("price", {}))
break
output.append(f"- {product_id}: {title} ({price_info}) [{status}]")
return "\n".join(output)
@mcp.tool()
def batch_create_inapp_products(products_json: str) -> str:
"""Create multiple one-time in-app products from a JSON array.
Each product needs: sku, localizations, price, currency_code.
Optionally: purchase_option_id (default: "default"), age_rating (default: "EVERYONE").
Args:
products_json: JSON array of product definitions.
Example: [
{"sku": "rezi_until_exam", "price": 1998, "currency_code": "RON",
"localizations": [
{"language": "en-US", "title": "Rezi - Until Exam", "description": "Full access"},
{"language": "ro", "title": "Rezidentiat", "description": "Acces complet"}
]}
]
Returns:
Summary of results for each product.
"""
products = json.loads(products_json)
results = []
for i, product in enumerate(products, 1):
try:
service = _get_service()
package_name = _get_package_name()
sku = product["sku"]
prod_price = product["price"]
prod_currency = product.get("currency_code", "USD")
info = _convert_prices(service, package_name, prod_price, prod_currency)
regions_version = info["regionsVersion"]
regional_configs, cap_warnings = _build_regional_configs(info["convertedRegionPrices"])
# Override the target region with the exact user-specified price
target_region = _CURRENCY_TO_REGION.get(prod_currency)
if target_region:
exact_units, exact_nanos = _price_to_units_nanos(prod_price)
for cfg in regional_configs:
if cfg["regionCode"] == target_region:
cfg["price"] = {
"currencyCode": prod_currency,
"units": str(exact_units),
"nanos": exact_nanos,
}
break
listings = [
{"languageCode": loc["language"], "title": loc["title"], "description": loc["description"]}
for loc in product["localizations"]
]
opt_id = product.get("purchase_option_id", "default")
prod_age_rating = product.get("age_rating", "EVERYONE")
body = {
"packageName": package_name,
"productId": sku,
"listings": listings,
"taxAndComplianceSettings": _age_rating_settings(prod_age_rating),
"purchaseOptions": [{
"purchaseOptionId": opt_id,
"buyOption": {"legacyCompatible": True},
"regionalPricingAndAvailabilityConfigs": regional_configs,
}],
}
request = service.monetization().onetimeproducts().patch(
packageName=package_name,
productId=sku,
body=body,
allowMissing=True,
updateMask="listings,purchaseOptions,taxAndComplianceSettings",
)
sep = "&" if "?" in request.uri else "?"
request.uri += f"{sep}regionsVersion.version={regions_version}"
request.execute()
caps = f" (capped: {len(cap_warnings)})" if cap_warnings else ""
results.append(f"[{i}/{len(products)}] OK: {sku} ({prod_price} {prod_currency}){caps}")
except Exception as e:
results.append(f"[{i}/{len(products)}] FAIL: {product.get('sku', 'unknown')} - {e}")
return "\n".join(results)
@mcp.tool()
def batch_activate_inapp_products(skus_json: str) -> str:
"""Activate multiple in-app products.
Args:
skus_json: JSON array of product IDs to activate.
Example: ["rezi_until_exam", "bac_until_exam"]
Returns:
Summary of results for each product.
"""
skus = json.loads(skus_json)
service = _get_service()
package_name = _get_package_name()
results = []
for i, sku in enumerate(skus, 1):
try:
service.monetization().onetimeproducts().purchaseOptions().batchUpdateStates(
packageName=package_name,
productId=sku,
body={
"requests": [{
"activatePurchaseOptionRequest": {
"packageName": package_name,
"productId": sku,
"purchaseOptionId": "default",
}
}]
},
).execute()
results.append(f"[{i}/{len(skus)}] OK: {sku} activated")
except Exception as e:
results.append(f"[{i}/{len(skus)}] FAIL: {sku} - {e}")
return "\n".join(results)
# ---------------------------------------------------------------------------
# Subscriptions
# ---------------------------------------------------------------------------
@mcp.tool()
def list_subscriptions() -> str:
"""List all subscription products for the app.
Returns:
List of all subscription products.
"""
service = _get_service()
package_name = _get_package_name()
result = service.monetization().subscriptions().list(