Build an Ecommerce MCP Server with TypeScript
Short answer
To build an ecommerce MCP server in TypeScript, register read-only tools (search, product detail, stock lookup) on an McpServer from @modelcontextprotocol/server (SDK v2, MCP revision 2026-07-28), validate every input with zod, and serve it over stdio. Our synthetic-catalog starter does exactly that, and its 20 scripted tests passed on Node 24.14.0 on 2026-11-29.
Key takeaways
- The current MCP TypeScript SDK is v2, split into
@modelcontextprotocol/serverand@modelcontextprotocol/client(2.4.0 on 2026-11-29). The single@modelcontextprotocol/sdkpackage (1.32.2) is the v1.x maintenance line and stops at spec 2025-11-25. - Start read-only: search, product detail, and variant stock cover most shopping questions without any write access.
- Zod schemas reject malformed IDs, unknown categories, and oversized limits before your code runs. We tested this.
- Tool annotations such as
readOnlyHintare hints to the client. The real permission boundary is what your code can reach. - Check your platform's native MCP or catalog endpoints first. Shopify and WooCommerce already publish their own.
What does an ecommerce MCP server actually do?
An ecommerce MCP server exposes catalog questions (what do you sell, what does this cost, is it in stock) as typed tools that an AI client can call. The Model Context Protocol (MCP) is an open protocol that lets AI applications discover and call tools, read resources, and use prompts provided by a server. A server does not make an AI system recommend your products. It only gives a connected client a reliable way to ask.
This tutorial builds the smallest useful version: four read-only tools over a synthetic catalog, served over stdio, with an automated test that spawns the server and calls every tool. The complete project is downloadable from the MCP commerce starter page. For the broader question of when a store needs MCP at all, read the MCP server guide for ecommerce first.
| Tool | Input (validated by zod) | Returns |
|---|---|---|
list_categories | none | Category names and the synthetic-data notice |
search_products | query 1–100 chars; optional category (enum), max_price_cents, in_stock_only; limit 1–20 (default 5) | Product summaries with minimum price in cents and in-stock flag |
get_product | product_id matching SYN-000 | One product with every variant, price, and stock count |
check_variant_stock | sku matching SYN-000-00 | Stock count and an in_stock / low_stock / out_of_stock label |
Do you need a custom MCP server, or does your platform already have one?
Check native options first, because many stores do not need custom code for catalog search. As of 2026-11-29, Shopify documents a Storefront Catalog MCP served at https://{storedomain}/api/ucp/mcp with search_catalog, lookup_catalog, and get_product tools, and WooCommerce documents an MCP integration that is in developer preview and runs through the WordPress MCP Adapter with WordPress permissions.
| Situation | Native path | When custom code is justified |
|---|---|---|
| Shopify store, standard catalog | Storefront Catalog MCP (documented by Shopify) | You need data Shopify does not hold, such as ERP stock by warehouse or compatibility tables |
| WooCommerce store | WooCommerce MCP (developer preview) | You need read-only tools scoped tighter than WordPress roles allow, or non-WooCommerce data |
| Headless or custom stack | Usually none | Most of the time: the catalog API exists, but no MCP layer does |
| PIM or ERP is the source of truth | Depends on vendor | When the AI-facing answer must come from the system of record, not the storefront |
If you are migrating from Shopify's older /api/mcp catalog and cart tools, those were removed. See the Shopify Storefront MCP migration guide. For a WooCommerce walk-through, see the WooCommerce MCP integration guide.
Which MCP TypeScript SDK version should you use?
Use SDK v2 (@modelcontextprotocol/server for servers, @modelcontextprotocol/client for clients) for new projects. On 2026-11-29 npm listed both at 2.4.0. The v2 package README says it is the stable line and implements MCP protocol revision 2026-07-28. The v1 package README says @modelcontextprotocol/sdk (1.32.2) is the maintenance line, implements the spec up to 2025-11-25, and will not get 2026-07-28 support.
| Package | Version | Role |
|---|---|---|
| Node.js | 24.14.0 (tested); engines set to >=22.18.0 | Runs .ts files directly with built-in type stripping. Only 24.14.0 was tested. |
@modelcontextprotocol/server | 2.4.0 | McpServer, tool registration, serveStdio |
@modelcontextprotocol/client | 2.4.0 (dev) | Test client and stdio client transport |
zod | 4.6.7 | Input and output schemas, imported as zod/v4 |
typescript | 6.0.3 (dev) | tsc --noEmit type check only |
@types/node | 24.19.4 (dev) | Node type definitions |
{
"name": "mcp-commerce-starter",
"version": "0.1.0",
"private": true,
"description": "SYNTHETIC DEMO: read-only ecommerce MCP server over a fictional product catalog (TypeScript, MCP TypeScript SDK v2).",
"type": "module",
"license": "MIT",
"engines": {
"node": ">=22.18.0"
},
"scripts": {
"start": "node src/server.ts",
"test": "node --test test/smoke.test.ts",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@modelcontextprotocol/server": "2.4.0",
"zod": "4.6.7"
},
"devDependencies": {
"@modelcontextprotocol/client": "2.4.0",
"@types/node": "24.19.4",
"typescript": "6.0.3"
}
}How should catalog data be shaped for MCP tools?
Give every product a stable ID, every variant a stable SKU, and store prices as integer minor units (cents) with an explicit currency. Floating-point prices cause rounding errors, and unstable IDs break any follow-up call an agent makes. The same rules apply to feeds; see stable product IDs and variants.
{
"id": "SYN-007",
"title": "Granite Mid Hiking Boot",
"category": "footwear",
"description": "Waterproof mid-height boot with lugged outsole.",
"brand": "Example Outfitters (synthetic)",
"currency": "USD",
"variants": [
{
"sku": "SYN-007-01",
"color": "Brown",
"size": "9",
"price_cents": 15900,
"stock": 41
},
{
"sku": "SYN-007-02",
"color": "Brown",
"size": "10",
"price_cents": 15900,
"stock": 1
},
{
"sku": "SYN-007-03",
"color": "Brown",
"size": "11",
"price_cents": 15900,
"stock": 17
},
{
"sku": "SYN-007-04",
"color": "Brown",
"size": "12",
"price_cents": 15900,
"stock": 0
}
]
}The data layer (src/catalog.ts) loads this file once and exposes pure functions: searchProducts, getProduct, getVariant, and availability. Keeping the data access separate from the MCP wiring means you can swap the JSON file for a platform API later without touching the tool definitions.
export function searchProducts(opts: SearchOptions): ProductSummary[] {
const terms = opts.query.toLowerCase().split(/\s+/).filter(Boolean);
return products
.filter((p) => {
const haystack = `${p.title} ${p.description} ${p.category}`.toLowerCase();
if (!terms.every((t) => haystack.includes(t))) return false;
if (opts.category && p.category !== opts.category) return false;
const s = summarize(p);
if (opts.maxPriceCents !== undefined && s.min_price_cents > opts.maxPriceCents) return false;
if (opts.inStockOnly && !s.in_stock) return false;
return true;
})
.slice(0, opts.limit)
.map(summarize);
}
// ...
// Coarse availability label. Exact counts are returned too, but a real store
// may prefer to expose only the label so it does not reveal inventory depth.
export function availability(stock: number): "in_stock" | "low_stock" | "out_of_stock" {
if (stock <= 0) return "out_of_stock";
if (stock <= 3) return "low_stock";
return "in_stock";
}How do you expose a product catalog as MCP tools?
Call server.registerTool(name, config, handler) once per tool. The config holds a description the model reads, a zod inputSchema, an optional outputSchema, and annotations. The handler receives already-validated arguments and returns content (text for the model) plus structuredContent (typed JSON for the client).
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";
import {
availability,
catalogNotice,
categories,
getProduct,
getVariant,
searchProducts,
} from "./catalog.ts";
// Every tool is read-only, idempotent, and touches nothing outside catalog.json.
const READ_ONLY = {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
} as const;
const productId = z
.string()
.regex(/^SYN-\d{3}$/, "Product IDs look like SYN-001")
.describe("Product ID from search_products, e.g. SYN-007");
const sku = z
.string()
.regex(/^SYN-\d{3}-\d{2}$/, "SKUs look like SYN-001-01")
.describe("Variant SKU from get_product, e.g. SYN-007-02");
const summarySchema = z.object({
id: z.string(),
title: z.string(),
category: z.string(),
min_price_cents: z.number().int(),
currency: z.string(),
in_stock: z.boolean(),
variant_count: z.number().int(),
});
function json<T extends Record<string, unknown>>(output: T) {
return {
content: [{ type: "text" as const, text: JSON.stringify(output) }],
structuredContent: output,
};
}
function notFound(message: string) {
return { content: [{ type: "text" as const, text: message }], isError: true };
}server.registerTool(
"search_products",
{
title: "Search products",
description:
"Keyword search over the synthetic demo catalog. Returns product summaries with prices in integer cents. Read-only.",
inputSchema: z.object({
query: z.string().trim().min(1).max(100).describe("Keywords, for example: rain jacket"),
category: z.enum(categories as [string, ...string[]]).optional(),
max_price_cents: z.number().int().positive().max(1_000_000).optional(),
in_stock_only: z.boolean().default(false),
limit: z.number().int().min(1).max(20).default(5),
}),
outputSchema: z.object({ results: z.array(summarySchema), total_returned: z.number().int() }),
annotations: READ_ONLY,
},
async ({ query, category, max_price_cents, in_stock_only, limit }) => {
const results = searchProducts({
query,
category,
maxPriceCents: max_price_cents,
inStockOnly: in_stock_only,
limit,
});
return json({ results, total_returned: results.length });
},
);- Descriptions are instructions. The model chooses tools from their descriptions, so say what the tool does, that it is read-only, and what units prices use.
- Return both forms.
structuredContentmust matchoutputSchemawhen one is declared. The text copy helps clients that only show text. - Fail as a tool result, not an exception. Unknown IDs return
isError: truewith a plain message, so the model can recover. The test checks this.
server.registerTool(
"check_variant_stock",
{
title: "Check variant stock",
description:
"Return the stock level and availability label for one variant SKU. Synthetic data, not live inventory. Read-only.",
inputSchema: z.object({ sku }),
outputSchema: z.object({
sku: z.string(),
product_id: z.string(),
title: z.string(),
color: z.string(),
size: z.string(),
price_cents: z.number().int(),
stock: z.number().int(),
availability: z.enum(["in_stock", "low_stock", "out_of_stock"]),
}),
annotations: READ_ONLY,
},
async ({ sku }) => {
const hit = getVariant(sku);
if (!hit) return notFound(`No variant with SKU ${sku} in the synthetic catalog.`);
const { product, variant } = hit;
return json({
sku: variant.sku,
product_id: product.id,
title: product.title,
color: variant.color,
size: variant.size,
price_cents: variant.price_cents,
stock: variant.stock,
availability: availability(variant.stock),
});
},
);How do you validate MCP tool inputs with zod?
Constrain every argument as tightly as the business allows: regex for identifiers, enums for categories, integer bounds for prices and limits, and length limits for free text. The SDK validates arguments against the schema before your handler runs, so malformed input never reaches the data layer.
| Argument | Rule | Tested rejection |
|---|---|---|
product_id | /^SYN-\d{3}$/ | "DROP TABLE products" rejected |
sku | /^SYN-\d{3}-\d{2}$/ | Covered by the same pattern; not separately tested |
category | z.enum(...) built from the catalog | "weapons" rejected |
limit | integer 1–20, default 5 | 500 rejected |
query | trimmed string, 1–100 chars | Not separately tested |
max_price_cents | positive integer up to 1,000,000 | Not separately tested |
Validation is not authorization. A perfectly valid product_id can still point at something a given caller should not see, such as a B2B price list. Once real data is involved, add a server-side permission check per tool. Authentication for ecommerce MCP servers covers that layer.
How do you limit what a commerce MCP server can do?
Limit the server by what it can reach, not only by what it says. The starter can read one JSON file. It has no network client, no database credentials, no write tools, and no environment secrets, so even a confused model cannot place an order or change a price through it.
- Annotations are hints. Every tool sets
readOnlyHint: true,destructiveHint: false,idempotentHint: true,openWorldHint: false. The SDK documentation says annotations do not change how the SDK runs the tool. Clients may use them for consent prompts. - stdio for local use. The MCP security best practices (revision 2026-07-28) recommend the stdio transport for locally run servers, because it limits access to the MCP client that launched the process.
- stdout is the protocol. Log to stderr only. A stray
console.logcorrupts the JSON-RPC stream. - Exact stock is a business decision. The starter returns stock counts and a coarse label. Many stores should expose only the label.
- No state handles. The starter has no cart. If you add one, the security guidance says servers must not treat possession of a cart or workflow handle as authentication, and should bind handles to the verified user.
// stdout carries the protocol, so diagnostics go to stderr only.
serveStdio(createServer, { onerror: (err) => console.error("[mcp-commerce-starter]", err) });
console.error("[mcp-commerce-starter] serving synthetic catalog over stdio");Can you test a commerce MCP server locally?
Yes. The starter's test uses the SDK's own client to spawn the server as a child process over stdio, list its tools, and call each one, which is the same path a desktop MCP host uses. It runs the full suite twice, once pinned to revision 2026-07-28 and once with the default 2025-era handshake.
- 1
Download and unzip
Get the starter zip. It contains the source, synthetic catalog, test, and README, with no
node_modules. - 2
Install
Run
npm installwith Node 22.18 or later (we tested 24.14.0). - 3
Run the tests
Run
npm test. It spawnssrc/server.tsover stdio and calls every tool under both protocol eras. - 4
Type-check
Run
npm run typecheckto runtsc --noEmitagainst the SDK's published types. - 5
Connect a host (optional)
Point an MCP-capable host at
node /absolute/path/src/server.tsand try the test prompts below. We did not test a specific desktop host.
// Smoke test: spawns the real server over stdio and calls each tool through an MCP client.
// The same suite runs twice: once pinned to MCP protocol revision 2026-07-28 ("modern")
// and once with the SDK client's default 2025-era initialize handshake ("legacy").
// Run with: npm test
import { describe, test, after, before } from "node:test";
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
const serverPath = fileURLToPath(new URL("../src/server.ts", globalThis._importMeta_.url));
type Structured = Record<string, any>;
const eras = [
{ label: "protocol 2026-07-28 (pinned)", expected: "2026-07-28", options: { versionNegotiation: { mode: { pin: "2026-07-28" as const } } } },
{ label: "legacy 2025-era handshake (SDK default)", expected: "2025-11-25", options: {} },
];
for (const era of eras) {
describe(era.label, () => {
const client = new Client({ name: "smoke-test", version: "0.1.0" }, era.options);
before(async () => {
const transport = new StdioClientTransport({ command: process.execPath, args: [serverPath] });
await client.connect(transport);
});
after(async () => {
await client.close();
});
// ...
test("search_products finds the rain shell", async () => {
const res = await client.callTool({ name: "search_products", arguments: { query: "rain jacket" } });
const out = res.structuredContent as Structured;
assert.equal(out.total_returned, 1);
assert.equal(out.results[0].id, "SYN-003");
});
// ...▶ protocol 2026-07-28 (pinned)
✔ negotiates the expected protocol version
✔ lists exactly four read-only tools
✔ search_products finds the rain shell
✔ search_products applies category, price, and stock filters
✔ get_product returns variants
✔ check_variant_stock reports out_of_stock for a zero-stock SKU
✔ unknown product returns a tool error, not a crash
✔ malformed product_id is rejected by zod validation
✔ limit above 20 is rejected
✔ unknown category is rejected
▶ legacy 2025-era handshake (SDK default)
✔ (same 10 tests)
ℹ tests 20
ℹ pass 20
ℹ fail 0Which prompts should you use to test an ecommerce MCP server?
Use prompts that each force a specific tool, one that chains tools, and one that asks for something the server must not do. Scripted tests prove the tools work. Prompts show whether the descriptions lead a model to the right tool.
| Prompt | Expected tool path | What it checks |
|---|---|---|
| "What product categories does this store have?" | list_categories | Basic discovery |
| "Find a rain jacket under $160 that is in stock." | search_products with max_price_cents: 16000, in_stock_only: true | Whether the model converts dollars to cents |
| "Show every variant of SYN-007 and which sizes are available." | get_product | Variant-level answers |
| "Is SKU SYN-001-02 in stock?" | check_variant_stock | Out-of-stock handling (this SKU has 0) |
| "Find a two-person tent and a sleeping pad. What would both cost?" | Two search_products calls, then arithmetic | Multi-step use; no checkout implied |
| "Delete product SYN-003." | None | The model should say it has no tool for this |
To inspect the tool list a client sees, including descriptions and schemas, use the MCP tool inspector.
What changes before an MCP server touches real store data?
Almost everything around the tools changes; the tool shapes mostly survive. The starter is deliberately a local, unauthenticated, synthetic demo. A production server adds a real data source, authorization, transport hardening, and monitoring.
| Area | Starter (synthetic demo) | Production requirement |
|---|---|---|
| Data | Static JSON, loaded at startup | Platform, PIM, or ERP API with freshness rules and caching |
| Transport | stdio, local only | Streamable HTTP behind TLS if remote, with rate limits |
| Auth | None | MCP authorization per the 2026-07-28 spec; tokens must be issued for your server (no token passthrough) |
| Scopes | n/a | Least-privilege scopes, starting with read-only discovery |
| Writes | None | Carts or checkout only through a reviewed design; see agentic checkout integration |
| Observability | stderr log line | Per-tool latency, error rates, and audit logs with correlation IDs |
If MCP is not the right interface for a given client, a plain API may be simpler; MCP vs REST for ecommerce compares them. If you want us to build the production version on your catalog, see MCP server development.
Frequently asked questions
Is @modelcontextprotocol/sdk still the right package?
For new servers, no. On 2026-11-29 the v1 package README described @modelcontextprotocol/sdk 1.32.2 as the maintenance line that implements the spec up to 2025-11-25. New work should use v2: @modelcontextprotocol/server and @modelcontextprotocol/client, both 2.4.0 on that date.
Does the starter work with MCP protocol revision 2026-07-28?
Yes, in our test. A v2 client pinned to 2026-07-28 negotiated that revision and all ten tool tests passed. The same server also served the client's default 2025-era handshake, which negotiated 2025-11-25.
Why are prices in cents?
Integer minor units avoid floating-point rounding errors and make comparisons exact. The tool descriptions say prices are in cents so the model converts "$160" to 16000. Always return the currency with the amount.
Can I run this without TypeScript compilation?
Yes. The project runs .ts files directly with Node's built-in type stripping, which is why it avoids TypeScript-only syntax such as enums. We tested on Node 24.14.0. The typecheck script is optional and only checks types.
Does publishing an MCP server get my products into ChatGPT or Google AI Mode?
No. An MCP server is a tool interface that a connected client can call. Inclusion in commercial AI shopping surfaces follows each platform's own feeds, programs, and approvals, which are separate from whether you run an MCP server.
Should the server return exact stock counts?
Only if you are comfortable exposing inventory depth to anyone who can call the tool. The starter returns both the count and a coarse label for demonstration. Many stores should return only in_stock, low_stock, or out_of_stock.
How do I add authentication?
For a remote HTTP deployment, follow the MCP authorization specification for your protocol revision and the security best practices: accept only tokens issued for your server, and request least-privilege scopes. Our MCP authentication guide covers the ecommerce-specific choices.
Can I reuse the code commercially?
Yes. The starter is MIT licensed and its catalog is synthetic, so there is no third-party data in it. Replace the catalog and add the production controls listed above before using it with real data.
Move from a demo to your catalog
Tell us your platform, where product and stock data live, and which AI clients you want to support. We will check the native options first.
Related
- TypeScript Ecommerce MCP StarterDownload the tested synthetic-catalog project.
- MCP Servers for EcommerceWhen a store needs MCP, and what it should expose.
- MCP Server Authentication for EcommerceAuthorization, scopes, and token handling.
- MCP vs REST API for EcommerceChoose the right interface for each client.
- MCP Tool InspectorReview tool names, descriptions, and schemas.
- MCP Server DevelopmentProduction MCP servers on your catalog.
Sources
- MCP security best practices (revision 2026-07-28)
- MCP specification, revision 2026-07-28
- MCP TypeScript SDK v2 documentation: tools
- @modelcontextprotocol/server on npm
- @modelcontextprotocol/sdk on npm (v1.x maintenance line)
- Shopify: Storefront Catalog MCP
- WooCommerce MCP (developer preview)
- Agent Commerce Optimization: MCP commerce starter (synthetic demo)
Platform capabilities, eligibility, and specifications change. Sources were checked on 2026-11-29; confirm the current primary documentation before scoping an implementation. See our editorial policy and methodology.