PyMC Marketing MCP
This server provides a decision-safe MCP interface for Bayesian marketing science, letting agents register data, fit/validate MMM and CLV models, run diagnostics, and use decision-grade budget and customer-value tools only when statistical gates pass.
Dataset readiness: register, inspect, and validate CSV/Parquet marketing datasets before modeling.
Marketing Mix Modeling (MMM): fit real Bayesian MMMs with configurable adstock, saturation, priors, seasonality, controls, and panel dimensions.
Model lifecycle: check model status, archive models, compare models, select best models via LOO/WAIC/stacking, and get diagnostic gate results.
Decision safety:
diagnose_mmmmust pass before budget optimization, simulation, or flighting tools will run.Measurement & validation: cross-validate MMMs, calibrate with lift test experiments, evaluate prior sensitivity, and recommend next measurements.
Marketing insights: get channel contributions, incremental ROAS, response curves, and posterior plots (PNG/SVG).
Budget decision science: simulate budget changes, optimize budgets with constraints, and optimize weekly media flighting schedules.
Customer Lifetime Value (CLV): fit purchase frequency models (BG/NBD, sBG), monetary value models (Gamma-Gamma), predict expected purchases, probability alive, expected spend, churn-risk cohorts, and estimate CLV.
Deprecated legacy CLV tools:
fit_clv_modelandpredict_customer_clvremain available for compatibility.Background jobs: submit, inspect, list, and cancel asynchronous MMM fitting jobs; resume and recover durable worker jobs.
Artifact and evidence support: posterior plots cached as MCP resources, and model/dataset provenance is tracked through status and comparison tools.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PyMC Marketing MCP fit an MMM to my data and analyze channel contributions"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PyMC Marketing MCP
Decision-safe Bayesian marketing science for MCP-compatible agents
LLMs can explain marketing data. They should not invent marketing science
PyMC Marketing MCP gives AI agents a controlled interface to PyMC-Marketing for Marketing Mix Modeling, Bayesian decision support, experimentation, budget allocation, customer lifetime value, and durable analytical workflows
The design boundary is deliberate
the agent frames the business question, chooses an allowed operation, and explains the evidence
PyMC-Marketing, PyMC, and ArviZ compute model-dependent quantities
this project owns validation, persistence, authorization, diagnostic policy, decision gates, provenance, jobs, and MCP contracts
decision-grade actions stop when the statistical evidence is not strong enough
This is not a thin tool wrapper around a probabilistic library, and it is not an autonomous media-buying agent
What you can do today
src/marketing_mcp/capabilities.py is canonical for capability and resource names and maturity; the public surface is generated into docs/CAPABILITIES.md. Treat that generated inventory as the derived reference for current capability totals, maturity, and evidence instead of copying a fixed count into this README
Capability maturity is evidence-backed, so an exposed tool is not automatically considered stable
Area | What the MCP can do | Representative capabilities |
Dataset readiness | Register, inspect, fingerprint, and validate modeling data |
|
MMM | Fit models, inspect status, compare models, calibrate with lift tests, and evaluate sensitivity |
|
Diagnostics | Run the mandatory statistical decision gate |
|
Measurement | Cross-validate models and suggest evidence-gathering work |
|
Decision science | Contributions, incremental ROAS, scenarios, budget allocation, and weekly flighting |
|
CLV | Purchase, churn, monetary-value, and lifetime-value modeling |
|
Visual evidence | Produce posterior plot artifacts |
|
Durable work | Submit, inspect, list, cancel, resume, and recover background jobs |
|
Artifact exchange | Export model/dataset artifacts to an AI-client sandbox and clean expired server storage |
|
Agent evidence | Record and retrieve structured analytical or operational insights |
|
Scientific skill guidance | Route tasks to scientific workflows and inspect the skill dependency map |
|
Provenance | Inspect datasets, models, diagnostics, plots, CLV records, model lineage, and scientific-skill references through MCP resources |
|
Some capabilities above are still experimental. Check the generated inventory before treating a capability as verified behavior
Related MCP server: simba-mcp
Why this project exists
A useful marketing agent needs more than access to a model
It needs a boundary between reasoning about marketing and claiming a statistically supported decision
Business question
|
v
AI agent
|
v
MCP tool or resource
|
v
validation + authentication + tenant authorization
|
v
application service
|
v
PyMC-Marketing / PyMC / ArviZ
|
v
posterior evidence + diagnostics
|
v
decision policy
|
v
structured result + warnings + provenanceThe model library owns the math. The MCP owns the rules around when that math may be used as decision evidence
Decision safety is a runtime rule
The repository separates descriptive analytical outputs from decision-grade actions
For example, a fitted MMM is not automatically allowed to drive budget optimization. diagnose_mmm persists the current decision status, and gated tools such as simulate_budget, optimize_budget, and optimize_flighting refuse to execute when the model does not satisfy the decision contract
The important rule is simple
model fitted != model approved for decisionsThe gate does not claim that an approved model proves causal truth. It establishes whether the repository permits a defined class of downstream decisions under the current diagnostics contract
Read docs/DECISION-INTEGRITY.md and docs/STATISTICAL-SAFETY.md before extending model-dependent decision behavior
What the project deliberately does not do
The current runtime does not provide unrestricted autonomous marketing control
It does not
let an LLM replace PyMC-Marketing for model-dependent calculations
allow arbitrary shell, SQL, Python, or callback execution through MCP tools
bypass diagnostics because a caller asks to "continue anyway"
change priors, model families, variables, or diagnostic thresholds until a model passes
treat a recent KPI movement as proof that something is broken
mutate Google Ads, Meta Ads, LinkedIn Ads, or other ad-platform campaigns as a current public capability
infer production readiness from the presence of tests or planning documents
These restrictions are product behavior, not prompt conventions
Quick start
Requirements
Python 3.12 or 3.13
Install the development environment
git clone https://github.com/imMamdouhaboammar/pymc-marketing-mcp.git
cd pymc-marketing-mcp
uv sync --frozen --extra devRun the synthetic demo
uv run marketing-mcp-demo --fastStart the MCP server over stdio
uv run marketing-mcp --transport stdioLocal stdio intentionally runs as a trusted local principal. Use an authenticated security profile for remote HTTP access
Runtime modes
Local stdio
Use this for local MCP clients and development
uv run marketing-mcp --transport stdioLocal Streamable HTTP
Use loopback HTTP for development
uv run marketing-mcp \
--transport streamable-http \
--host 127.0.0.1 \
--port 8000The runtime exposes the MCP endpoint at /mcp, plus /health, /health/live, and /health/ready
Private HTTP with an API key
The http-private-api-key profile requires authentication before startup
export MARKETING_MCP_SECURITY_PROFILE=http-private-api-key
export MARKETING_MCP_API_KEY='replace-with-a-real-secret'
uv run marketing-mcp \
--transport streamable-http \
--host 127.0.0.1 \
--port 8000Do not commit credentials or place them in examples, fixtures, logs, screenshots, or release evidence
Production OAuth profile
The codebase includes an http-production-oauth profile with asymmetric token verification, required scopes, and tenant claim mapping
Production deployment is not release-approved. External identity-provider integration and exact-commit release evidence remain part of the production-readiness contract
Use docs/SECURITY.md, docs/DEPLOYMENT-GCP.md, and docs/PRODUCTION-READINESS.md instead of treating this README as a production deployment runbook
Background jobs
Expensive statistical work can be represented as durable jobs rather than tying computation to one MCP request
Run a standalone worker with
uv run marketing-mcp-worker --poll-interval 2.0The current job implementation includes durable job records, semantic idempotency, cancellation, leases, fencing, retry limits, and stale-lease recovery
Production claims about distributed workers remain subject to the G2 and H4 evidence requirements in docs/PRODUCTION-READINESS.md
Typical MMM workflow
A normal model-to-decision path is
1. register_dataset
2. inspect_dataset
3. validate_dataset
4. fit_mmm or submit_fit_mmm_job
5. diagnose_mmm
6. inspect descriptive posterior evidence
7. use decision-grade tools only when the gate permits them
8. retain dataset, model, configuration, package, and decision provenanceA useful agent should not skip directly from fit_mmm to a budget recommendation
Example decision path
fit_mmm
|
v
diagnose_mmm
|
+-- rejected/caution requiring stop --> explain evidence or request more measurement
|
+-- decision access permitted ------> simulate_budget / optimize_budget / optimize_flightingTypical CLV workflow
The CLV surface separates purchase behavior from monetary value instead of hiding both behind one generic prediction call
1. fit_purchase_model
2. predict_expected_purchases / predict_probability_alive
3. fit_value_model when monetary modeling is required
4. predict_expected_spend
5. estimate_customer_lifetime_valueLegacy compatibility wrappers remain visible in the capability inventory as deprecated rather than pretending they are current first-choice APIs
Architecture
The project is structured so the MCP transport does not own marketing or statistical behavior
src/marketing_mcp/
MCP transport
mcp/
tools + resources + envelopes + request context
|
v
Application services
services/
datasets + modeling + diagnostics + decisions + plots + CLV + jobs
|
+--------------------+
| |
v v
Domain policy Computation adapters
domain/ adapters/
validation PyMC-Marketing boundary
diagnostics PyMC / ArviZ integration
decision rules
| |
+----------+---------+
|
v
Persistence + artifacts
storage/ + repositories/ + jobs/ + credentials/
Cross-cutting boundaries
security/ principals + scopes + tenant authorization + OAuth
observability/ structured logs + metrics + traces
http/ health + request safety + credential control API
schemas/ typed public contractsThe main ownership rule is that orchestration may coordinate domain owners, but it should not duplicate their math, persistence semantics, or authorization rules
Read docs/ARCHITECTURE.md for the current and target topology
Persistence and artifacts
The default local runtime uses SQLite-backed metadata, jobs, and credential state with local artifact storage
The repository also contains a shared-SQL persistence path used by the production-hardening work. Multi-instance production readiness must be judged against the current persistence and artifact evidence, not the existence of an adapter alone
Important local paths can be configured with environment variables including
MARKETING_MCP_INGEST_DIR
MARKETING_MCP_ARTIFACT_DIR
MARKETING_MCP_METADATA_DB
MARKETING_MCP_MAX_DATASET_MB
MARKETING_MCP_PERSISTENCE_BACKEND
MARKETING_MCP_SHARED_SQL_URLSee src/marketing_mcp/config.py for the runtime configuration contract
Security model
Remote access is request-scoped and tenant-aware
The security boundary includes
authenticated principals propagated into MCP tool execution
scope checks mapped to public tools
object and tenant authorization
backend-controlled API-key verification and revocation
asymmetric OAuth verification for the production profile
request safety middleware
structured-log secret redaction
fail-closed startup checks for insecure HTTP configurations
A valid token or API key does not imply access to every tenant or every operation
Read docs/SECURITY.md for the full contract and known production gaps
Observability
The runtime includes
structured JSON logging
secret scrubbing
low-cardinality metrics
trace context propagation
liveness and readiness endpoints
Identifiers useful for correlation belong in logs or trace context where allowed, not in metric labels that create uncontrolled cardinality
Production exporters, alerts, and SLO evidence are tracked separately from the local observability implementation
Capability maturity
Public capability status comes from src/marketing_mcp/capabilities.py and is rendered into docs/CAPABILITIES.md
stable executable evidence is referenced for the capability
experimental exposed, but the required evidence is incomplete or absent
deprecated retained for compatibility and scheduled for removalThe registry, actual MCP discovery, generated documentation, and evidence references are checked for drift in tests
Do not hand-edit docs/CAPABILITIES.md
Current maturity
Advanced beta / release-candidate implementation, not release-approved
The repository contains substantial hardening work across scientific correctness, recovery, remote security, observability, release evidence, agent quality, and upstream compatibility
That does not make every release gate green for the current commit
A gate is green only when machine-collected evidence for the exact commit being assessed proves the required property. Older test runs, historical release notes, a passing local command, or the existence of a test file are not substitutes for current release evidence
Current gate interpretation lives in docs/PRODUCTION-READINESS.md
Planned next capability: Marketing Reconciliation Engine
The repository now has an implementation-ready plan for a bounded reconciliation capability
This is planned work, not a current MCP runtime capability
The v1 direction is intentionally narrow
detect machine-checkable operational, data-integrity, and decision-safety incidents
persist incident evidence and action attempts
run shadow-first
allow automatic mutation only for explicit low-risk internal recipes
verify every repair before reporting an incident as healed
escalate when evidence is uncertain
keep commercial ad-platform mutation outside v1
The first planned automatic repair is subject-scoped expired worker-lease recovery. The plan explicitly rejects a free-form autonomous growth agent and arbitrary campaign actuation
Planning artifacts
Do not expose planned reconciliation tools or scopes as current capability until implementation, discovery, authorization, and evidence tests land together
Verify the repository
Install the development dependencies first
uv sync --frozen --extra devFast and integration-oriented checks
uv run pytest -m "not statistical" -vStatistical checks
These run real PyMC-Marketing sampling and can take materially longer than ordinary unit tests
uv run pytest -m statistical -vStatic checks
uv run ruff check src tests scripts
uv run pyrightDocumentation and capability drift
uv run python scripts/generate_capability_inventory.py --check
uv run python scripts/check_docs_drift.pyFull suite and package build
uv run pytest -v
uv buildPassing these commands locally is useful engineering evidence. It is not by itself a production release approval
Repository map
.
├── src/marketing_mcp/
│ ├── adapters/ PyMC-Marketing computation boundary
│ ├── credentials/ API-key issuance, verifier storage, and revocation
│ ├── domain/ validation, diagnostics, allocation, and decision policy
│ ├── http/ health, request safety, and control-plane routes
│ ├── jobs/ durable jobs, idempotency, leases, fencing, worker CLI
│ ├── mcp/ tools, resources, envelopes, context, and task adapter
│ ├── observability/ structured logging, metrics, and tracing
│ ├── schemas/ typed public contracts
│ ├── security/ principals, scopes, authorization, OAuth, redaction
│ ├── services/ application workflows
│ └── storage/ SQLite migrations and durable stores
├── tests/
│ ├── contract/ public and decision-gate contracts
│ ├── integration/ transport, auth, persistence, resource, and worker behavior
│ ├── release/ G0-G5 and H0-H6 release assertions
│ ├── statistical/ real PyMC-Marketing statistical invariants
│ └── unit/ focused domain and service tests
├── docs/
│ ├── plans/ active implementation plans and engineering ledgers
│ ├── release-evidence/ machine-collected release proof
│ └── README.md documentation truth map
├── scripts/ documentation, capability, release, and verification tooling
├── pyproject.toml package and tool configuration
└── task_plan.md broader implementation and phase trackerDocumentation map
Start with the document that owns the question you are asking
Question | Source of truth |
What is publicly exposed | |
What does each tool promise | |
How is the code organized | |
When may model outputs drive decisions | |
What statistical rules are non-negotiable | |
How does authentication and tenancy work | |
What is actually release-ready | |
What evidence supports release claims | |
How should conflicting documentation be interpreted | |
What are engineers building next |
Plans are targets. Tests are evidence for the behavior they actually exercise. Release evidence is commit-specific. The current source and executable checks outrank historical prose
Dependency policy
The supported package contract currently targets
Python >=3.12,<3.14
PyMC-Marketing >=1.0.0,<2
MCP Python SDK >=2,<3
Pydantic >=2.12,<2.13
NumPy >=2,<3
Pandas >=2.2,<3
ArviZ >=0.21,<2The upstream canary can test newer dependency combinations without silently widening the committed package contract
PyMC-Marketing 2.x should be adopted only after adapter, statistical, plotting, optimization, calibration, and persisted-artifact compatibility is proven and any required migration is explicit
Historical releases
Earlier v0.3 and v0.4 material remains in CHANGELOG.md and docs/FINAL-REVIEW.md for provenance
Historical release notes do not establish the readiness of the current commit
License
Apache License 2.0. See LICENSE
Available Tools
33 toolsarchive_modelB
Archive a model record and update its lifecycle state.
Inputs: input (required).
calibrate_mmmA
Calibrate an existing MMM using experimental lift test measurements. Produces a new calibrated model artifact linked via lineage.
Inputs: input (required).
cancel_jobA
Cancel a currently queued or running background job.
Inputs: job_id (required).
compare_modelsA
Compare diagnostics, predictive metrics, and lineage across multiple fitted MMMs.
Inputs: input (required).
cross_validate_mmmB
Run rolling Time-Slice Cross-Validation with PyMC-Marketing. Evaluates out-of-sample predictive RMSE/NRMSE across multiple temporal folds.
Inputs: input (required).
diagnose_mmmA
Mandatory diagnostic gate. Checks sampler health plus posterior predictive coverage, predictive error, and residual behavior before decision tools may run.
Inputs: model_id (required).
estimate_customer_lifetime_valueA
Estimate discounted net present Customer Lifetime Value (CLV) by combining a fitted purchase model (e.g. BG/NBD) and monetary value model (e.g. Gamma-Gamma).
Inputs: config (required).
evaluate_prior_sensitivityA
Evaluate sensitivity of commercial conclusions (channel rank order and iROAS) under alternative adstock and saturation priors.
Inputs: input (required).
fit_clv_modelA
Fit a Bayesian Customer Lifetime Value (CLV) model on RFM transaction data. (Deprecated: prefer fit_purchase_model or fit_value_model).
Inputs: config (required).
fit_mmmB
Fit a real Bayesian Marketing Mix Model with PyMC-Marketing using typed, controlled configuration. No arbitrary Python is accepted. Supports adstock types: geometric (default), delayed, weibull_cdf, weibull_pdf, binomial, none. Supports saturation types: logistic (default), tanh, tanh_baselined, michaelis_menten, hill, hill_sigmoid, inverse_scaled_logistic, log, root, none. Per-channel adstock/saturation overrides can be set via channel_priors.
Inputs: config (required).
fit_purchase_modelA
Fit a Bayesian purchase/transaction frequency model (BG/NBD or Shifted Beta-Geometric). Normalizes user column names to canonical RFM attributes.
Inputs: config (required).
fit_value_modelC
Fit a Bayesian monetary value transaction model (Gamma-Gamma) on repeat customer spending. Requires frequency and average monetary value columns.
Inputs: config (required).
get_channel_contributionsA
Return posterior channel contribution summaries from the fitted PyMC-Marketing model. Does not fabricate estimates.
Inputs: model_id (required).
get_churn_risk_cohortsA
Identify customers at churn risk from a fitted CLV model. Returns customers whose Bayesian P(alive) is below the specified threshold. Lower threshold = higher confidence of churn. Default threshold: 0.3.
Inputs: model_id (required), threshold_p_alive.
get_incremental_roasA
Return total and marginal iROAS from PyMC-Marketing's official incrementality API, including posterior uncertainty. No ad-hoc LLM ROAS calculation.
Inputs: model_id (required).
get_job_statusA
Retrieve the execution status, results, or error details of an asynchronous job.
Inputs: job_id (required).
get_model_statusB
Get persisted model fit state, lineage, and safe failure information.
Inputs: model_id (required).
get_posterior_plotsA
Generate posterior visualization plots from a fitted and approved MMM. Returns base64-encoded PNG/SVG images in the evidence envelope and caches them as MCP resources at marketing://models/{model_id}/plots/{plot_type}. Supported plot types: saturation_curves, waterfall_decomposition, actual_vs_predicted, channel_contribution_share.
Inputs: config (required).
get_response_curvesB
Return response/saturation information sampled by PyMC-Marketing rather than raw posterior arrays.
Inputs: model_id (required).
inspect_datasetA
Inspect a registered dataset before MMM configuration. Returns candidate targets, channels, controls, frequency, and data issues.
Inputs: dataset_id (required).
list_jobsC
List recent asynchronous background jobs for the active tenant.
Inputs: limit, status.
optimize_budgetC
Use PyMC-Marketing budget optimization under channel or dimension-cell constraints, then compare baseline and recommended posterior responses. Requires a diagnosed model.
Inputs: config (required).
optimize_flightingA
Optimize a dynamic weekly media flighting schedule over a planning horizon, accounting for adstock carryover dynamics, channel spend constraints, target iROAS floors, and profit-maximization objectives. The model must be approved or approved_with_caution before optimization. Returns a week-by-week spend table per channel, posterior response distribution, and net-profit estimates.
Inputs: config (required).
predict_customer_clvA
Generate per-customer CLV predictions from a fitted BG/NBD model. (Deprecated: prefer predict_expected_purchases or estimate_customer_lifetime_value).
Inputs: config (required).
predict_expected_purchasesB
Predict expected future purchase counts per customer from a fitted purchase model (BG/NBD).
Inputs: config (required).
predict_expected_spendA
Predict average transaction monetary spend per customer from a fitted Gamma-Gamma value model.
Inputs: config (required).
predict_probability_aliveB
Estimate probability of customer retention/alive from a fitted purchase or churn model.
Inputs: config (required).
recommend_next_measurementA
Recommend evidence-gathering options when model/data signals imply material uncertainty. It can explicitly return that no single experiment is implied.
Inputs: model_id (required).
register_datasetA
Register a local CSV or Parquet marketing dataset and return a stable dataset reference.
Inputs: path (required).
select_best_modelC
Compare multiple fitted MMMs using PSIS-LOO, WAIC, or Bayesian stacking weights via ArviZ. All models must be fitted on the same dataset. Returns ranked specifications, LOO/WAIC scores, and recommended model ID. Methods: loo (PSIS-LOO), waic (WAIC), stacking (BMA weights), all (run all three).
Inputs: config (required).
simulate_budgetC
Evaluate the exact requested channel or dimension-cell scenario with posterior response sampling. Rejected models are blocked.
Inputs: config (required).
submit_fit_mmm_jobB
Submit an asynchronous MMM fitting job that executes in the background without blocking.
Inputs: config (required), idempotency_key.
validate_datasetA
Run MMM-specific data quality, panel-shape, and identifiability checks. This must pass before fitting.
Inputs: dataset_id (required), date_column (required), target_column (required), channel_columns (required), +2 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 33 tools
Most tools target distinct actions, but several overlap: deprecated fit_clv_model and predict_customer_clv duplicate newer fit/predict tools, compare_models and select_best_model both compare fitted MMMs, and predict_probability_alive overlaps somewhat with get_churn_risk_cohorts. Descriptions do help clarify boundaries, so the set is usable but not sharply distinct.
The dominant pattern is consistent snake_case verb_noun (fit_, predict_, get_, optimize_, register_), which is easy to follow. Minor deviations exist, such as recommend_next_measurement, get_churn_risk_cohorts, and inconsistent use of the mmm suffix (fit_mmm vs get_channel_contributions), but the overall style remains predictable.
With 33 tools, this is a large surface and above the 25+ threshold that typically signals overload. The count is inflated by deprecated tools, separate synchronous/asynchronous fit paths, and many highly granular getter tools, making the set feel heavier than necessary even for a complex marketing analytics domain.
The toolset covers the main MMM lifecycle well: data registration, validation, fitting, diagnosis, cross-validation, calibration, comparison, budget optimization, plotting, and archival. CLV coverage also includes fitting, prediction, and churn risk. Minor gaps such as no generic model listing/deletion tool and no CLV-specific dataset validation are noticeable but workable.
Maintenance
Related MCP Connectors
Query your data in plain English or SQL, build datasets, and fit Bayesian models.
Causal check on AI agent claims, from ad-spend/ROAS lift to any decision: pass, caution or hold.
Analytics your AI agent can actually use. Track, experiment, and optimize via MCP.
AI marketing agent for Google Ads, Meta, GA4, TikTok, LinkedIn, Shopify, HubSpot and more.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA Model Calling Protocol server that enables LLMs to perform rigorous Bayesian analysis and probabilistic reasoning, including inference, model comparison, and predictive modeling with uncertainty quantification.4MIT
- -licenseNot gradedqualityBmaintenanceConnects AI assistants to marketing mix models, enabling natural language data upload, performance modeling, budget optimization, and scenario testing.-

Simba MCP Serverofficial
AlicenseAqualityAmaintenanceEnables AI assistants to interact with Bayesian marketing mix models through natural language, including data upload, model building, result inspection, budget optimization, and scenario planning.9443 PyPI3MIT- AlicenseAqualityBmaintenanceDeterministic marketing math for AI agents: 62 engines that compute LTV:CAC, CAC payback, pipeline coverage, A/B test significance, budget allocation, pricing and retention from your own numbers. Runs locally with Node 18+, makes no network calls and stores no data.51MIT