Audience: LLM-driven engineering agents and human developers
Amazon Ads MCP is a Python framework (Python ≥3.10) for integrating Amazon Advertising API with Model Context Protocol (MCP) servers. This project provides a complete toolkit for building AI-powered advertising applications with comprehensive campaign management, reporting, and optimization capabilities.
- Ensure Python ≥3.10 and uv are installed
uv syncto install dependencies- Start the server:
docker compose up -d - Connect Claude to the MCP server (HTTP):
claude mcp add amazon-ads-mcp -- python -m amazon_ads_mcp.server --transport http --port 9080
- Verify:
claude mcp listand use/mcpinside Claude
CRITICAL: Always run these commands in sequence before committing:
# Install dependencies
uv sync # Install dependencies
# Validate code
uv run ruff check --fix # Lint and auto-fix
uv run pytest # Run full test suiteAll must pass - tests/linting must be clean before committing.
- Preambles: Send a brief 1–2 sentence note before running tool commands.
- Plans: Use
TodoWritefor multi-step work; keep exactly onein_progressstep. - Edits: Use
EditorMultiEditto modify files; keep changes focused and avoid unrelated edits. - Testing: Run the smallest relevant tests first; do not fix unrelated failures.
- Sandboxing: Assume workspace-write FS and restricted network; prefer local resources over external APIs unless keys are present.
Follow these steps for reliable outcomes in Claude contexts:
- Understand & Plan
- Clarify task type: API integration, MCP connectivity, Docker, tests, or GitHub workflow.
- Post a short preamble and, for multi-step work, create a minimal
TodoWritewith exactly onein_progressstep.
- Connect & Verify (MCP + Server)
- Start server:
docker compose up -d(Amazon Ads MCP athttp://localhost:9080). - Add MCP to Claude (HTTP):
claude mcp add amazon-ads-mcp -- python -m amazon_ads_mcp.server --transport http --port 9080
- Verify in Claude:
claude mcp listthen/mcp→ run a tool (e.g., list profiles).
- Implement Safely
- Prefer the smallest viable change; touch only relevant files.
- Use
EditorMultiEditfor edits. Only rungitif explicitly requested. - Keep environment secrets out of logs; mask sensitive data.
- Test Incrementally
- Lint:
uv run ruff check --fix. - Targeted tests first:
uv run pytest tests/unit/test_specific.py. - Full suite if needed:
uv run pytest.
- Validate Behavior
- For MCP changes: exercise tools via
/mcpin Claude. - For Docker changes:
docker build -t amazon-ads-mcp .and check logs.
- Prepare Handoff
- If commits are requested: propose a branch name and show the exact commands; otherwise provide patch summary and affected files.
- Summarize changes, risks, and next steps in your final message.
Guardrails (Never Do)
- Do not push to
mainor force-push; avoid branch deletions. - Do not log secrets (API keys, tokens) or large payloads.
- Do not widen scope or refactor unrelated code.
Escalation Prompts (When Blocked)
- "I need permission to run networked commands/install packages; approve or provide offline alternative?"
- "Tests rely on external API keys; provide keys or allow me to skip/mark accordingly?"
- "MCP output exceeds token limits; can I raise
MAX_MCP_OUTPUT_TOKENS?"
Claude Command Cheatsheet
- List servers:
claude mcp list - Add server (HTTP):
claude mcp add amazon-ads-mcp -- python -m amazon_ads_mcp.server --transport http --port 9080 - In-session MCP menu:
/mcp - Read files:
/read <path>; Edit files:/edit <path>
| Path | Purpose |
|---|---|
src/amazon_ads_mcp/ |
Library source code (Python ≥ 3.10) |
├─server/ |
MCP server implementation and FastMCP integration |
├─auth/ |
Authentication providers (Direct, Openbridge) |
├─tools/ |
Amazon Ads tool implementations |
├─models/ |
Pydantic models for API responses |
├─middleware/ |
Authentication, OAuth, and sampling middleware |
└─utils/ |
HTTP client, OpenAPI handling, security utilities |
openapi/ |
OpenAPI specifications and transformations |
├─resources/ |
Individual API resource definitions |
tests/ |
Pytest test suite |
examples/ |
Example usage and demo scripts |
docker-compose.yaml |
Docker service configuration |
- Amazon Ads MCP Server:
- The HTTP listen port follows
PORTin.env(.env.exampleuses 9080); examples below usehttp://localhost:9080. - It connects to Amazon Ads API with proper authentication.
- The HTTP listen port follows
- Quick connect from host:
claude mcp add amazon-ads-mcp -- python -m amazon_ads_mcp.server --transport http --port 9080
- Verification:
claude mcp listto check health- In Claude, run
/mcpand call a tool (e.g., list profiles, get campaigns)
When modifying Amazon Ads functionality, changes typically affect:
- Campaigns (
cp_*tools for campaign management) - Profiles (Multi-account management and switching)
- Reporting (
reporting_*tools for performance metrics) - DSP (
dsp_*tools for programmatic advertising) - AMC (
amc_*tools for Amazon Marketing Cloud) - Authentication (OAuth flows, token management)
- File Downloads (HTTP download routes for exports and reports)
The report_fields tool provides bounded, opt-in access to the packaged
Ads API v1 field catalog (117 dimensions + 700 metrics with compatibility
graph). It closes the v1 field-discovery failure loop: v1 OpenAPI doesn't
enumerate query.fields, so LLMs used to guess and hit HTTP 400s.
list_report_fields stays as the curated-baseline tool (unchanged).
Discover fields:
report_fields(mode="query", category="metric", search="click", limit=25)
report_fields(mode="query", compatible_with=["campaign.id"])
report_fields(mode="query", fields=["metric.clicks"]) # detail lookup
Pre-flight a field list before AdsApiv1CreateReport:
report_fields(mode="validate",
operation="allv1_AdsApiv1CreateReport",
validate_fields=["metric.clicks", "campaign.id"])
# → unknown_fields, missing_required, incompatible_pairs, suggested_replacements
Pre-flight the requested date range too — pass start_date/end_date
(ISO YYYY-MM-DD) alongside exactly one time grain in validate_fields:
report_fields(mode="validate",
validate_fields=["hour.value"],
start_date="2026-05-01", end_date="2026-06-10")
# → time_window: {grain, within_max_report_pull, within_historical_data,
# earliest_allowed_start, problems[...]}
The window is checked against that grain's max_report_pull span cap and
historical_data lookback (the curated category="time" overlay), using
calendar-correct month math. A window with problems flips valid to false.
start_date/end_date are validate-mode only and must be supplied together;
a date range with zero or more than one time grain raises INVALID_MODE_ARGS.
Or check a named preset against the grain's supported set (case-insensitive):
report_fields(mode="validate",
validate_fields=["hour.value"],
date_range_preset="Last 90 days")
# → preset: {grain, supported: false, supported_presets: [...]}; valid=false
date_range_preset is validate-mode only and also requires exactly one time
grain. It composes with start_date/end_date — both pre-flights run and
either failing flips valid to false.
Slim the response when compatibility arrays aren't needed (autocomplete, name-only enumeration, existence checks):
report_fields(mode="query", category="metric", search="cost", limit=20,
drop=["compatible_dimensions", "incompatible_dimensions"])
drop semantics:
- Optional list of top-level keys to omit from every record in
fields[]. - Query-mode only. Passing
dropinmode="validate"raisesINVALID_MODE_ARGS— validate carries no field records to shape, so the call is treated as a contract violation, not a silent no-op. - Values are validated against the
ReportFieldEntryallowlist. Typos (e.g."compatable_dimensions") raiseINVALID_MODE_ARGSrather than silently keeping the bytes the caller meant to strip. The error message lists the allowed keys. - Required keys (e.g.
field_id) are still removable — the allowlist gates known vs unknown record keys, not required vs optional. - Top-level response metadata (
total_matching,parsed_at,stale_warning, …) is not a record key and cannot be dropped. - Default behavior (no
drop) is byte-identical to the prior shape. - Byte-cap measurement factors
dropin, so dropping populated arrays can also avoid description clipping when the post-drop payload fits.
category="time" returns the curated, doc-sourced time-grain catalog: the
seven v1 reporting time dimensions (hour/date/day/week/month/year/ dateRange.value) enriched with date_range_presets, historical_data, and
max_report_pull per grain. These windows are NOT in the OpenAPI spec, so
they close the time-axis equivalent of the field-discovery 400 loop (e.g.
hour.value caps at a 14-day pull; date.value allows a 120-day pull but a
15-month lookback). The overlay is a curated constant in
report_fields_v1_catalog.py (not generated dimensions.json), so it does
not affect catalog-drift checks, and it surfaces ONLY under category="time"
— dimension/metric/fields=[...] output stays byte-identical.
report_fields(mode="query", category="time") # all 7 grains + windows
report_fields(mode="query", category="time",
drop=["date_range_presets"]) # name + window only
category="filter" is accepted but returns empty (no filter records in the
v1 catalog yet) — use list_report_fields(operation=...) for filter
baselines on other report APIs.
| Variable | Default | Purpose |
|---|---|---|
ENABLE_REPORT_FIELDS_TOOL |
true |
Master toggle for the report_fields tool and the associated async hint |
LIST_REPORT_FIELDS_MAX_BYTES |
16384 |
Hard byte cap on query/detail responses (serializer boundary) |
LIST_REPORT_FIELDS_STALE_DAYS |
90 |
Threshold for stale_warning on catalog freshness |
AMAZON_ADS_DEBUG_TOOLS |
false |
When true, exposes the internal _report_fields_debug tool |
ALLOW_CATALOG_COUNT_DROP |
false |
CI override for catalog-refresh minimum-content floors |
uv run pytest -m "not slow" # fast suite (default local)
uv run pytest -m slow # wheel-content + smoke (CI only)
The slow marker is registered in pyproject.toml but the global
addopts = "-v" is untouched — slow-test filtering is invocation-level.
When .build/adsv1_specs/ is updated, regenerate the packaged catalog:
# Regenerate + validate + enforce production floors:
uv run python -m amazon_ads_mcp.build.refresh_v1_catalog \
--source .build/adsv1_specs \
--dest src/amazon_ads_mcp/resources/adsv1 \
--validate --production-floors
# Commit the regenerated artifacts:
git add src/amazon_ads_mcp/resources/adsv1/
git commit -m "chore: refresh v1 catalog"The CI catalog-drift job runs refresh_v1_catalog --check on every PR,
so a missed refresh after editing the source fails fast with a clear
drift message. catalog-idempotency guards determinism; catalog-negative
guards the failure paths; wheel-smoke proves the files ship in the wheel.
Behavioral guarantees locked by tests:
- Loader opens only four named files under
resources/adsv1/; strays and.tmpfiles are never enumerated. catalog_meta.jsonis the commit signal — SHA-256 of on-diskdimensions.jsonandmetrics.jsonmust match the manifest, in either direction of runtime/catalog version mismatch → fail closed.report_fields(mode="query")responses are sorted ascending byfield_id; byte cap enforced at the serializer boundary clips descriptions but never drops fields.
The MCP server provides HTTP endpoints for downloading exported files. This separates the control plane (MCP tools) from the data plane (HTTP file serving).
MCP Tools (Control Plane) HTTP Routes (Data Plane)
───────────────────────── ────────────────────────
list_downloads() ──▶ GET /downloads
get_download_url() ──▶ GET /downloads/{path}
download_export() ──▶ Saves to profile-scoped storage
All downloaded files are stored under profile-specific directories:
data/
├── profiles/
│ ├── {profile_id_1}/
│ │ ├── exports/campaigns/
│ │ └── reports/async/
│ └── {profile_id_2}/
│ └── ...
- Download a report or export: Use the OpenAPI tools to create and poll, then
download_exportto save the file - List available files: Use
list_downloadstool - Get download URL: Use
get_download_urltool - Download via HTTP: Open URL in browser or use curl
| Endpoint | Method | Description |
|---|---|---|
/downloads |
GET | List all files with download URLs |
/downloads/{path} |
GET | Download a specific file |
/downloads?type=reports |
GET | Filter by resource type |
- Profile isolation: Files scoped to active profile only
- Path traversal prevention:
Path.relative_to()validation - Bearer token auth: Optional
AMAZON_ADS_DOWNLOAD_AUTH_TOKEN - Sensitive file blocking:
.env, credentials, keys blocked - Size limits: Configurable max file size
- Be brief and to the point. Focus on what the code does, not extensive explanations.
- NEVER use "This isn't..." or "not just..." constructions. State what something IS directly.
- When documenting Amazon Ads operations, focus on the API aspects and MCP integration.
- Mock external API calls for unit tests
- Use integration tests sparingly (require real credentials)
- Test authentication flows thoroughly
- Verify region routing works correctly
- Test error handling for API rate limits
import pytest
from amazon_ads_mcp.auth import AuthManager
async def test_auth_flow():
auth_manager = AuthManager()
token = await auth_manager.get_access_token(
profile_id="test_profile"
)
assert token is not None
# Clean up
await auth_manager.cleanup()# Build and test Docker image
docker build -t amazon-ads-mcp .
docker run --rm amazon-ads-mcp python -c "from amazon_ads_mcp import __version__; print('OK')"- Symptom:
Failed to connect http://localhost:9080- Cause: Server not running or port mismatch.
- Fix: Check
docker compose up -dand verify port mapping.
- Check Docker:
docker psshould showamazon-ads-mcpon port 9080. - Increase logs: Set debug environment variables in
docker-compose.yaml.
- OpenAPI specs in
openapi/resources/define available operations - Run processing scripts after spec updates
- Use transformation files for customization
- Minify specs for production deployment
# Step 1: Build Docker image
docker compose build
# Step 2: Run container
docker compose up -d
# Step 3: View logs
docker compose logs -f# Direct run with uv
uv run python -m amazon_ads_mcp.server --transport http --port 9080
# With Docker
docker compose up -d# Authentication
export AMAZON_ADS_AUTH_METHOD="direct" # or "openbridge" / "kuudo"
export AMAZON_ADS_CLIENT_ID="your-client-id"
export AMAZON_ADS_CLIENT_SECRET="your-client-secret"
export AMAZON_ADS_REFRESH_TOKEN="your-refresh-token"
# For Openbridge
export OPENBRIDGE_API_KEY="your-api-key"
export OPENBRIDGE_ACCOUNT_ID="your-account-id"
# Server configuration
export TRANSPORT="http" # or "stdio"
export HOST="0.0.0.0"
export PORT="9080"# MCP runtime behavior
export MCP_TIMEOUT=300
export MAX_MCP_OUTPUT_TOKENS=25000
export MCP_MASK_ERROR_DETAILS=true
export MCP_ON_DUPLICATE_TOOLS=warn# Code mode replaces tool catalog with meta-tools (98% token reduction)
# See docs/code-mode.md for full documentation
export CODE_MODE=true # Master switch (default: true)
export CODE_MODE_INCLUDE_TAGS=true # Include tag browsing (default true)
export CODE_MODE_MAX_DURATION_SECS=30 # Sandbox timeout
export CODE_MODE_MAX_MEMORY=50000000 # Sandbox memory (50MB)
# The Docker image ships with the code-mode extra pre-installed
# (fastmcp[code-mode], which pulls pydantic-monty for the Monty sandbox).
# For non-Docker installs (or custom images), install it explicitly:
# pip install "fastmcp[code-mode]>=3.1.0"
# Set CODE_MODE=false to expose the full tool catalog directly instead.The execute meta-tool runs LLM-generated Python in a Monty sandbox
with a single external function in scope: await call_tool(name, params).
- Errors are catchable. Failures from
call_toolare normalized toRuntimeError("<OriginalType>: <message>")and surface inside the sandbox sotry/except RuntimeError:works as expected. The LLM can probe N candidate tool names in a singleexecuteblock instead of paying N round trips. - The dispatch loop (
MontyDispatchSandboxProviderinsrc/amazon_ads_mcp/server/code_mode.py) drives Monty viastart()+resume()rather than upstreamrun_async()so that external-function exceptions actually reach the sandbox's surroundingtry/except.run_async()would bubble them out and abort the script.
Sandbox guardrails (verified, documented in the EXECUTE_DESCRIPTION
constant — keep aligned with reality):
- No network (
urllib,requests,httpx,socketblocked) — every external interaction must go throughcall_tool. - No filesystem I/O (
open(),pathlib,os.*blocked). print()output may be discarded depending on the client path — return data via the script's final expression instead.asyncio.sleepis unavailable by design — chainawait call_toolcalls (e.g. report-status polling) instead of sleeping.withworks for pure-Python context managers; not foropen(...).json.dumps(default=...)may trip on Pydantic models; callmodel_dump()first.
# Background task execution for long-running tools (enabled by default)
# When enabled, clients can request background execution and poll for progress
# Uses in-memory backend (tasks lost on restart); Redis backend available for persistence
export ENABLE_TASKS=true # Master switch (default: true)# Download authentication (optional - if unset, auth is disabled)
export AMAZON_ADS_DOWNLOAD_AUTH_TOKEN="your-secret-token"
# Maximum file size for downloads (default: 512MB)
export AMAZON_ADS_DOWNLOAD_MAX_FILE_SIZE=536870912
# Allowed file extensions (optional whitelist, comma-separated)
export AMAZON_ADS_DOWNLOAD_ALLOWED_EXTENSIONS=".json,.csv,.txt,.gz"
# Base download directory (default: ./data)
export AMAZON_ADS_DOWNLOAD_DIR="./data"# Canonical external URL of this server. When set, all public links
# (download URLs, OAuth redirect_uri fallbacks) use this value. Required
# for any deployment behind a proxy or load balancer.
export AMAZON_ADS_PUBLIC_BASE_URL="https://ads.example.com"
# Only honor X-Forwarded-Proto / X-Forwarded-Host from the client when
# explicitly enabled. Do NOT enable on a directly internet-exposed server:
# a malicious client can otherwise forge public URLs pointing at their
# own domain.
export AMAZON_ADS_TRUST_FORWARDED_HEADERS="false"
# OAuth redirect URI (required for non-localhost deployments). Must match
# the value registered with Amazon Ads.
export OAUTH_REDIRECT_URI="https://ads.example.com/auth/callback"# Token Persistence (disabled by default for security)
# When false (default): Tokens stored in memory only, lost on restart
# When true: Refresh tokens cached to disk/volume, persist across restarts
export AMAZON_ADS_TOKEN_PERSIST="false" # Set to "true" to enable persistence
# Token Encryption (required when AMAZON_ADS_TOKEN_PERSIST=true)
# If not set, a random key is auto-generated and stored alongside tokens
# For production: Generate with `python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`
export AMAZON_ADS_ENCRYPTION_KEY="your-44-char-base64-key"
# Plaintext Storage (INSECURE - testing only!)
# Only enable if cryptography library is unavailable AND you accept the risk
export AMAZON_ADS_ALLOW_PLAINTEXT_PERSIST="false" # Never set to "true" in productionSecurity Implications of Token Persistence:
When AMAZON_ADS_TOKEN_PERSIST=true:
- ✅ Convenience: Refresh tokens survive container restarts (no re-authentication)
⚠️ Risk: Tokens are encrypted but stored with their decryption key on same volume⚠️ Risk: Anyone with filesystem/volume access can potentially extract tokens- 🔒 Mitigation: Set
AMAZON_ADS_ENCRYPTION_KEYfrom external secrets manager - 🔒 Best Practice: Use in-memory storage (default) unless persistence is required
Recommended Configurations:
# Development (local laptop): In-memory is usually sufficient
AMAZON_ADS_TOKEN_PERSIST=false
# Shared/Production: Either in-memory OR persistence with external key
AMAZON_ADS_TOKEN_PERSIST=false # Preferred if feasible
# OR
AMAZON_ADS_TOKEN_PERSIST=true
AMAZON_ADS_ENCRYPTION_KEY=${VAULT_SECRET} # From secrets manager- Python ≥ 3.10 with full type annotations
- Use Pydantic for data models
- Follow Amazon Ads API patterns
- Security-first approach for credentials
- Efficient pagination for large result sets
- Reference Amazon Ads operations explicitly (e.g., "fix: campaign creation with targeting")
- Mention OpenAPI updates when relevant
- Include Docker changes if applicable
- Keep messages brief and focused
- Default branch is
main(protected). Do not push directly tomain. - Create focused branches using kebab-case:
feat/<area>-<short-desc>(new capability)fix/<area>-<short-desc>(bug fix)docs/<topic>(documentation only)chore/<task>(infra, deps, refactors)
- Optionally append issue ID:
feat/auth-oauth-flow-#123.
- Use Conventional Commits for clear history and automatic versioning:
feat: ...- New feature (triggers minor version bump)fix: ...- Bug fix (triggers patch version bump)feat!: ...orBREAKING CHANGE:- Breaking change (triggers major version bump)docs: ...- Documentation onlyrefactor: ...- Code restructuringtest: ...- Adding testschore: ...- Maintenance tasksperf: ...- Performance improvementsci: ...- CI/CD changes
- Keep commits small and atomic; reference issues (e.g.,
Closes #123).
# Patch version bump (0.1.0 → 0.1.1)
git commit -m "fix: resolve token refresh issue"
git commit -m "fix: handle empty response from API"
# Minor version bump (0.1.0 → 0.2.0)
git commit -m "feat: add new authentication method"
git commit -m "feat: implement batch operations for campaigns"
# Major version bump (0.1.0 → 1.0.0)
git commit -m "feat!: redesign API interface (BREAKING CHANGE)"
git commit -m "feat: new auth system
BREAKING CHANGE: removed support for v1 authentication"Note: Pushes to main automatically trigger releases based on commit messages.
- Open PRs early as Drafts; mark Ready when CI is green and reviews addressed.
- PR title follows Conventional Commit style (used for squash-merge title).
- Include in description:
- Context/motivation and linked issues
- Summary of changes (user-visible + internal)
- Testing steps and results (commands, screenshots/log excerpts as needed)
- Risk assessment and rollback plan
- Apply labels:
area:*,semver:*(patch/minor/major),type:*(feat/fix/docs).
PR Checklist:
-
uv run ruff check --fixclean -
uv run pytestgreen (or targeted subset justified) - Docker builds if relevant (
docker build -t amazon-ads-mcp .) - Docs updated (README/AGENTS) if behavior changes
- Prefer Squash & Merge to keep a tidy history; ensure the squash title is a good Conventional Commit.
- Rebase from
mainbefore merging; resolve conflicts locally. - Require at least one approval; two for high-risk changes (auth, API operations).
git clone <repo>
cd amazon-ads-mcp
uv sync- Linting:
uv run ruff check --fix - Type Checking:
uv run mypy src/ - Testing:
uv run pytest - Coverage:
uv run pytest --cov=amazon_ads_mcp
# Build image
docker build -t amazon-ads-mcp .
# Run with Docker Compose
docker compose up -d
# Check logs
docker compose logs -f
# Shell into container
docker exec -it amazon-ads-mcp /bin/bash# Error: "Failed to connect to MCP server" or "Connection refused"
# Recovery steps:
docker ps | grep amazon-ads # Check if container running
docker compose restart # Restart container
docker logs amazon-ads-mcp --tail 50 # Check for startup errors
# If still failing:
docker compose down && docker compose up -d
claude mcp list # Verify MCP connection# Error: "401 Unauthorized" or "Invalid refresh token"
# Check environment variables
docker compose exec amazon-ads-mcp env | grep AMAZON_ADS
# Test authentication directly
uv run python -c "
from amazon_ads_mcp.auth import AuthManager
auth = AuthManager()
print(auth.test_connection())
"# Error: "FAILED tests/test_auth.py::test_oauth_flow"
# Debug approach:
uv run pytest -xvs tests/test_auth.py::test_oauth_flow # Run single test verbose
uv run pytest --pdb tests/test_auth.py # Drop into debugger on failure# Error: "failed to solve: executor failed running"
docker system prune -f # Clean Docker cache
docker build --no-cache -t amazon-ads-mcp . # Force rebuild| Operation | Expected Time | Warning Threshold | Action if Slow |
|---|---|---|---|
| Docker Build | 2-3 min | >5 min | Clean Docker cache, check network |
| Unit Tests | 5-10s | >30s | Run subset, check fixtures |
| Integration Tests | 20-40s | >90s | Mock external calls |
| API Call (single) | <500ms | >2s | Check network, API throttling |
| Bulk Operation (100 items) | <5s | >15s | Use batch API endpoints |
| MCP Tool Call | <1s | >3s | Check payload size |
# Profile slow tests
uv run pytest --durations=10
# Check Docker resource usage
docker stats amazon-ads-mcp --no-stream
# Monitor MCP response time
time claude mcp list# Test API connectivity
curl -H "Amazon-Advertising-API-ClientId: $AMAZON_ADS_CLIENT_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
https://advertising-api.amazon.com/v2/profiles
# Check rate limits
uv run python -c "
from amazon_ads_mcp.utils import check_rate_limits
check_rate_limits()
"# Run MCP in debug mode
DEBUG=true uv run python -m amazon_ads_mcp.server
# Test MCP server directly
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | \
uv run python -m amazon_ads_mcp.server | jq
# Check registered tools
uv run python -c "
from amazon_ads_mcp.server import get_registered_tools
print(get_registered_tools())
"# Check all required env vars
uv run python -c "
import os
required = ['AMAZON_ADS_CLIENT_ID', 'AMAZON_ADS_CLIENT_SECRET']
for var in required:
val = os.getenv(var, 'NOT SET')
print(f'{var}: {\"SET\" if val != \"NOT SET\" else \"NOT SET\"}')
"
# Verify Python and package versions
python --version
uv pip show amazon-ads-mcp | grep Versionsrc/amazon_ads_mcp/**/*.py # Main application code
tests/**/*.py # Test files
openapi/resources/*.json # API specifications
.env # Local environment (never commit)
examples/*.py # Example scripts
dist/* # Build artifacts
*.egg-info/* # Package metadata
__pycache__/* # Python bytecode
.pytest_cache/* # Test cache
.ruff_cache/* # Linter cache
.mypy_cache/* # Type checker cache
pyproject.toml # Dependencies & metadata
Dockerfile # Build process (test locally first)
docker-compose.yaml # Service configuration
.github/workflows/* # CI/CD (test in fork first)
openapi/resources/*.transform.json # API transformations
- Authentication fails: Check environment variables and refresh token
- Region routing errors: Verify profile region settings
- Docker build fails: Ensure all dependencies are in pyproject.toml and run
uv lock - Import errors: Run
uv syncto install dependencies - Rate limit errors: Implement exponential backoff
- MCP timeout: Increase
MCP_TIMEOUTenvironment variable - File download 401: Set
AMAZON_ADS_DOWNLOAD_AUTH_TOKENor check Bearer token - File download 404: Verify active profile with
get_active_profile, file may be in different profile - Download "No active profile": Call
set_active_profilebefore downloading files
- Use batch operations for bulk API calls
- Implement caching for frequently accessed data
- Configure connection pooling for HTTP clients
- Use pagination efficiently for large result sets
- Minimize OpenAPI spec size in production
Before committing, verify:
- All tests pass (
uv run pytest) - Linting clean (
uv run ruff check) - Docker builds successfully (
docker build -t amazon-ads-mcp .) - Environment variables documented for new features
- Security considerations addressed (credentials, API keys)
- Install deps:
uv sync - Start server:
docker compose up -d - Add MCP to Claude (HTTP):
claude mcp add amazon-ads-mcp -- python -m amazon_ads_mcp.server --transport http --port 9080
- Verify:
claude mcp listand/mcp - Run tests:
uv run pytest - Lint:
uv run ruff check --fix