shopify-multistore

cocodwork/shopify-multistore Checked 2 days ago

Query several Shopify stores in parallel with one set of credentials.

You have several regional Shopify stores — genuinely separate stores, each with its own admin, its own catalogue, its own currency. Not one store using Shopify Markets to serve multiple regions. Separate stores. You want to ask an AI agent a question that spans all of them: *what's our stock position across every market*, *which products underperform in one region but not the others*, *push this inventory number to the right store*. One question, every store, one answer. If that's you, keep reading.

Summary extracted from the README.

Giving an AI agent access to several Shopify stores at once

Why the official connector can't do it, and the ~200 lines that can.


Is this you?

You have several regional Shopify stores — genuinely separate stores, each with its own admin, its own catalogue, its own currency. Not one store using Shopify Markets to serve multiple regions. Separate stores.

You want to ask an AI agent a question that spans all of them: what's our stock position across every market, which products underperform in one region but not the others, push this inventory number to the right store. One question, every store, one answer.

If that's you, keep reading. If you run a single store, or one store with Shopify Markets regions, you don't need any of this — the official connector already does what you want.

What you'll need

Two hard prerequisites. Check these before you spend an afternoon:

  1. Shopify Plus. Installing one app across multiple stores relies on custom distribution, which is a Plus feature. Without it you'll be creating and managing a separate app per store — possible, but a different and more tedious article.
  2. All stores under the same Shopify organization. The app and the stores must live in one organization for a single set of credentials to work across them.

Beyond that: Python 3, and no third-party packages. The whole thing runs on the standard library.

What you get

A thin client that fans one GraphQL query out across every store in parallel and hands back a {store: result} dictionary:

from shopify_multi import query

QUERY = """
{ shop { name currencyCode }
  productsCount { count } }
"""

results = query(QUERY)
for store, data in results.items():
    print(store, data["shop"]["currencyCode"], data["productsCount"]["count"])

That's the whole interface. Token acquisition, caching, rotation and per-store credential storage happen underneath, and you never think about them again.

The interesting part isn't the code — it's short enough that you could write it yourself in an afternoon if you knew the seven things in section 5, which is really what this article is for.


Why not just use the official connector?

Reasonable question, and it's where I started. The short answer: the connector is built around one store at a time, and that assumption goes all the way down.

It holds exactly one store

Connect the Shopify connector to your AI client and it authenticates against a single store. There's a switch-shop operation, which sounds like the answer — but switching revokes the token for the store you were on. It isn't a selector between several live connections. It's a move, not a copy.

So a cross-store question degrades into: connect to A, ask, switch, re-authorise, ask, switch, re-authorise... and by the time you're back at A, A is gone. For an agent that's supposed to answer one question over several stores, this doesn't work at all.

Running several MCP instances doesn't rescue it

The obvious workaround is to run one MCP server instance per store, each with its own OAuth session:

claude mcp add --transport http shopify-a https://setup.shopify.com/mcp
claude mcp add --transport http shopify-b https://setup.shopify.com/mcp

I tried this. It didn't work, I didn't troubleshoot it in any depth, and I went in a different direction instead.

"So why not write your own MCP server?"

You absolutely could, and it's the natural next step — the code here is exactly what such a server would wrap. I use it as a module because most of my usage is scripted reporting rather than conversation, and a plain function is easier to schedule and test than a protocol server.

If you want the agent to reach the stores conversationally, take this module and put an MCP server around it. The hard part — credentials, tokens, scopes, fanning out — is done. That part is the same either way, and it's the part with all the traps in it.

One more thing changed in 2026

Even if you decide to build your own, the ground moved underneath the old advice. Shopify retired legacy custom apps on 1 January 2026. You can no longer create one from the store admin, and there's no shpat_ token to copy out any more.

Nearly every tutorial you'll find still assumes you have that static token. You don't. What replaces it is a client_credentials grant, which is genuinely nicer — one set of credentials across every store — but it expires every 24 hours, which changes how you have to write the client.

That's the next section.


Getting a token in 2026

What used to work, and doesn't any more

The old recipe was: store admin → Settings → Apps → Develop apps → create a custom app → copy the Admin API access token, a long string starting with shpat_. Paste it into your script, done. That token never expired.

Shopify retired legacy custom apps on 1 January 2026. The Develop apps path no longer creates them, and there is no shpat_ token to copy out. If you're following any tutorial that starts with "paste your access token here", it was written before that date.

What replaces it

Create an app in the Dev Dashboard (dev.shopify.com/dashboard) rather than in a store admin. You get a Client ID and Client Secret, and you exchange them for a token at request time:

POST https://{shop}.myshopify.com/admin/oauth/access_token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=YOUR_ID&client_secret=YOUR_SECRET
{
  "access_token": "atkn_...",
  "expires_in": 86399
}

Two things about that response matter more than they look:

expires_in: 86399 — just under 24 hours. This is the single biggest behavioural difference from the old static token. Your client must now cache tokens and know when to throw them away. Half the traps in section 5 come from getting this wrong.

The token is per store. The {shop} in that URL changes per store, so you make this exchange once per store and hold one token each.

The bit that makes multi-store work

Here's the part worth understanding clearly, because it's easy to get backwards:

One set of credentials. One token per store.

The Client ID and Secret are shared across every store. The tokens they buy are not — each store issues its own, and each expires on its own clock.

What makes the shared credentials legal is custom distribution: a Plus feature that lets you install one app across multiple stores within the same Shopify organization. Set that up in the Dev Dashboard, then open the install link on each store.

Both halves of that sentence are load-bearing:

  • Same organization. Stores outside it can't be reached by this app, full stop.
  • Custom distribution. Without it you're back to an app per store, and the "one set of credentials" simplification disappears.

Scopes to request while you're in there

Adding a scope later means re-authorising every store by hand (section 5.1 explains why that's more annoying than it sounds), so think about it once, properly:

scope why
read_products catalogue, variants, SKUs
read_inventory stock levels
read_locations needed to tell locations apart — see 5.7
read_orders recent orders
read_all_orders anything older than 60 days. See 5.6 — this one fails silently.
write_inventory only if you intend to push stock back
write_products only if you intend to edit the catalogue

Request read scopes generously and write scopes reluctantly. A read scope you don't use costs nothing; a write scope you don't use is a way for a script bug to become a live-store incident.


The implementation

Roughly 200 lines, standard library only. Three problems to solve: where credentials live, when tokens get replaced, and how to fan a query out.

1. Credentials never touch the repo

On macOS, the Keychain works without any dependency:

import subprocess

def keychain_get(service: str, account: str) -> str | None:
    r = subprocess.run(
        ["security", "find-generic-password", "-s", service, "-a", account, "-w"],
        capture_output=True, text=True,
    )
    return r.stdout.strip() if r.returncode == 0 else None

Store them once, with input hidden so the secret never lands in your shell history:

security add-generic-password -s shopify-multi -a client_id  -w
security add-generic-password -s shopify-multi -a client_secret -w

Fall back to environment variables so the module still works on Linux and in CI. What you must not do is keep credentials in a file inside the repo — .gitignore protects you right up until the day you run git add -f, or clone the folder somewhere else, or hand it to someone.

2. Tokens: cache, but distrust the cache

A token lasts just under 24 hours, so caching is not optional — without it every query pays for a fresh exchange per store.

import json, os, time
from pathlib import Path

CACHE = Path.home() / ".cache" / "shopify-multi"
SAFETY_MARGIN = 300  # refresh 5 min early rather than fail mid-run

def cached_token(store: str) -> str | None:
    f = CACHE / f"token-{store}.json"
    if not f.exists():
        return None
    d = json.loads(f.read_text())
    if d["expires_at"] - time.time() < SAFETY_MARGIN:
        return None
    return d["access_token"]

def store_token(store: str, token: str, expires_in: int) -> None:
    CACHE.mkdir(parents=True, exist_ok=True)
    f = CACHE / f"token-{store}.json"
    f.write_text(json.dumps({"access_token": token,
                             "expires_at": time.time() + expires_in}))
    os.chmod(f, 0o600)

Three details worth copying:

  • SAFETY_MARGIN. Without it, a token that expires 4 seconds into a long run fails halfway through and you get a partial result that looks like a data problem.
  • chmod 0o600. These files are live credentials. Default permissions are too generous.
  • A force_refresh flag. You will need it the moment you change a scope — see 5.3, where a cached token quietly serves you yesterday's permissions.

3. Fanning out

The work is entirely network-bound, so threads are the right tool and the standard library has everything:

from concurrent.futures import ThreadPoolExecutor

def query(graphql: str, variables: dict | None = None) -> dict:
    stores = load_stores()
    with ThreadPoolExecutor(max_workers=len(stores)) as pool:
        futures = {pool.submit(_one, s, graphql, variables): s for s in stores}
        return {futures[f]: f.result() for f in futures}

The important design decision is what happens when one store fails. Raising kills the whole run and throws away the stores that succeeded — which is exactly wrong when you're querying several stores precisely because you want to compare them.

So each store catches its own failure and reports it in-band:

def _one(store, graphql, variables):
    try:
        return _post(store, graphql, variables)
    except Exception as e:
        return {"error": f"{type(e).__name__}: {e}"}

Callers check for "error" and carry on with the rest. A store being down, mid-reauth or missing a scope is a routine condition, not an exceptional one.

4. The certificate trap

On macOS, python3 often resolves to a python.org build that ships without CA root certificates, so every HTTPS call dies with CERTIFICATE_VERIFY_FAILED before you get anywhere near Shopify.

import ssl
def ssl_context():
    ctx = ssl.create_default_context()
    try:
        ctx.load_default_certs()
        if not ctx.get_ca_certs():
            raise ssl.SSLError("no CA certs")
    except Exception:
        import certifi                      # optional, only if you hit this
        ctx = ssl.create_default_context(cafile=certifi.where())
    return ctx

Note what this does not do: it never disables verification. Every StackOverflow answer to this error suggests verify=False or an unverified context. Don't — you're carrying live store credentials over that connection.


What the docs don't tell you

Seven things that cost me real time. None are in the official docs, and most of them fail in a way that points at the wrong cause.


1. Scopes live on the store installation, not the app version

This is the most costly one, because it fails silently and in the wrong direction.

You add write_inventory to your app, publish a new version, and reasonably assume the app can now write inventory. It can't. Publishing a version is not the same as a store granting the scope. Every store must re-open the install link and accept the widened permissions individually.

I found this the hard way: same app, same Client ID, and only one store could actually write. Check per store — never once:

{ currentAppInstallation { accessScopes { handle } } }

What I got back:

store scopes granted can write?
the one I'd re-authorised 15, incl. write_inventory / write_products yes
all the others 13, all read-only no

The fix is manual: Dev Dashboard → your app → custom distribution → copy the install link → open it on each store and accept.

2. write_X implies read_X, so your scope check will lie to you

Once a store grants write_products, Shopify stops listing read_products separately — it's implied. If your health check naively diffs "scopes I asked for" against "scopes I have", the upgraded store now looks broken:

store: missing read_products, read_inventory

That's the store with more access, not less. I chased this for a while before working out that the checker was wrong, not the store.

Fold write_X into read_X before comparing, and print the write scopes you actually hold so the output can't be misread:

def satisfied(granted: set[str], required: set[str]) -> bool:
    implied = {s.replace("write_", "read_", 1) for s in granted if s.startswith("write_")}
    return required <= (granted | implied)

3. Your token is cached for 24 hours — including its stale scopes

client_credentials returns a token with expires_in: 86399, just under a day. If you cache it (you should), widening a scope changes nothing until that cache expires. You'll re-authorise every store, re-run your check, and still be shown the old permissions.

Force a refresh, or delete the cached token, immediately after any scope change.

4. inventorySetQuantities changed in three ways in API 2026-07

Every pre-2026 example you'll find online is now broken, in three separate places:

  • ignoreCompareQuantity is gone. → Field is not defined on InventorySetQuantitiesInput
  • changeFromQuantity is now required (inside InventoryQuantityInput). Annoying, but it's a safety upgrade: you must read the current value and pass it back, so a concurrent edit by someone else fails instead of being silently overwritten by you.
  • @idempotent(key:) is mandatory — and it goes on the field, not the mutation. This cost me the most time of anything here, because putting it on the mutation is the intuitive placement and the error doesn't tell you where it actually belongs.
mutation($input: InventorySetQuantitiesInput!, $key: String!) {
  inventorySetQuantities(input: $input) @idempotent(key: $key) {
    inventoryAdjustmentGroup {
      reason
      changes { name delta quantityAfterChange }
    }
    userErrors { field message code }
  }
}

5. quantityAfterChange can come back null — don't verify with it

When name is "available", the returned quantityAfterChange may be null even on a completely successful write. Use it to confirm the write landed and you'll report false failures.

Read the value back instead:

inventoryItem {
  inventoryLevels(first: 10) {
    nodes {
      location { name }
      quantities(names: ["available"]) { name quantity }
    }
  }
}

6. Without read_all_orders you silently get only the last 60 days

This one is documented, but it's easy to skip while ticking scope boxes, and the failure is invisible: queries succeed, return data, and quietly omit everything older than 60 days. Any historical reporting built on top is wrong without ever raising an error.

If you care about history, ask for it up front. The stores I work with hold years of order history that is simply unreachable without this scope, and nothing tells you it's missing.

7. Multi-location stores need per-location reads

productVariant.inventoryQuantity is the sum across every location. If a store has more than one — a retail counter, a showroom, a decommissioned warehouse still holding stock — that number is not your sellable online inventory.

Go through inventory levels and filter to the location that actually fulfils online orders:

inventoryItem {
  inventoryLevels(first: 10) {
    nodes {
      location { name }
      quantities(names: ["available"]) { name quantity }
    }
  }
}

This is, incidentally, why several off-the-shelf reporting connectors get multi-location stores wrong — they read the summed field and never mention it.


Environment footnote

On macOS, if python3 resolves to a python.org build (3.13+), you may hit CERTIFICATE_VERIFY_FAILED on every HTTPS call — those builds ship without CA root certificates. Fall back to certifi when the default SSL context fails, rather than disabling verification.


Setup

git clone https://github.com/cocodwork/shopify-multistore.git
cd shopify-multistore

No pip install — there are no dependencies. Three steps:

1. Create the app. In the Dev Dashboard, create an app in the organization that owns your stores. Request the scopes from the table above. Under Distribution, choose custom distribution and copy the install link.

2. Install it on every store. Open that install link once per store and accept. Do not skip a store — an app version is not a granted scope (section 5.1).

3. Store your credentials and check.

mkdir -p ~/.config/shopify-multi
cp config.example.json ~/.config/shopify-multi/config.json
$EDITOR ~/.config/shopify-multi/config.json

security add-generic-password -s shopify-multi -a client_id -w
security add-generic-password -s shopify-multi -a client_secret -w

python3 -m shopify_multi check read_products read_inventory read_all_orders

Expected output:

  ok    store-a: 15 scopes, writes: write_inventory, write_products
  ok    store-b: 15 scopes, writes: write_inventory, write_products
  WARN  store-c: 13 scopes, read-only
        missing: read_all_orders
        (re-open the custom distribution install link on this store
        — publishing an app version does NOT grant scopes)

On Linux or in CI, set SHOPIFY_CLIENT_ID and SHOPIFY_CLIENT_SECRET instead of using the Keychain.

Tests

python3 -m unittest discover -s tests -v

17 tests, no dependencies, no network. They deliberately cover the cases that are awkward to produce against a live store:

  • a token sitting inside its expiry safety margin
  • a 401 arriving mid-query, and the single clean retry that follows
  • one store failing while the others succeed
  • write_X satisfying a read_X requirement (section 5.2), without hiding a scope that is genuinely absent

What they don't cover: whether Shopify's API actually responds the way this client assumes. That needs a real store — worth doing once against a development store before you rely on any of this.

Files

file what it is
shopify_multi.py the whole client, ~300 lines, standard library only
example.py stock position for one SKU across every store
config.example.json copy to ~/.config/shopify-multi/config.json
tests/test_client.py 17 offline tests

License

MIT — see LICENSE.

A note on scope

This solves one specific problem: several separate Shopify stores, one organization, one agent that needs to see all of them. It is not a general-purpose Shopify SDK and doesn't try to be. If you need pagination helpers, bulk operations, or webhook handling, use Shopify's own libraries — this is the thin layer that sits underneath the thing they don't cover.