Stackfable · MCP series, Part 6 (final)
Continuing the same shopping assistant through direct tool calling, an MCP server, an MCP client, multiple servers, and resources and prompts.
The core idea
Our shopping MCP server already exposes two tools, two resources, and one prompt. Until now, the Python chatbot started the server as a local subprocess and exchanged MCP messages through stdio. That works for the chatbot on the same machine, but another application cannot reach that subprocess through a URL.
To let other applications reach it, we must deploy the server at a URL and change the transport, not the shopping logic:
# Previous: local server
mcp.run(transport="stdio")
# New: remote server using the official MCP Python SDK v2
mcp.run(
transport="streamable-http",
host="0.0.0.0",
port=8080,
stateless_http=True,
json_response=True,
)On the host side, the client moves from a local subprocess definition to a remote URL:
# Before: Client(StdioServerParameters(...))
# After:
async with Client("https://YOUR-HOST/mcp") as client:
tools = await client.list_tools()
result = await client.call_tool("check_inventory", {"product_id": "kb-101"})The LLM tool-calling loop stays the same. The MCP client still discovers tools and invokes them, the host still translates results into Claude tool_result blocks, and the host still keeps conversation history. Only the network boundary changes.
flowchart LR
accTitle: Shopping assistant reaches a remote MCP server
accDescr: The user talks to a Claude shopping host, which talks to Claude and sends MCP requests through a client over HTTPS to a remote server backed by a product catalog.
U[User] --> H[Claude shopping host]
H <-->|Messages API| L[Claude]
H --> C[MCP client]
C -->|HTTPS /mcp| S[Remote MCP server]
S --> P[(Product catalog)]The deployment in the original course used legacy SSE because its Python SDK did not yet support Streamable HTTP. That historical instruction should not be copied into a new deployment. The current SDK supports Streamable HTTP and MCP protocol revision 2026-07-28. For new services, use /mcp, not a legacy /sse endpoint. See the official Python SDK server-running guide and 2026-07-28 protocol announcement.
1. What exactly are we deploying?
We are still using the fictional keyboard catalog introduced in Part 1:
| MCP capability | Name or URI | Purpose |
|---|---|---|
| Tool | search_products(query, max_price) | Match catalog products without stock |
| Tool | check_inventory(product_id) | Look up quantity |
| Resource | shop://catalog | Read a catalog snapshot |
| Resource template | shop://products/{product_id} | Read one product's public details |
| Prompt | recommend_keyboard | Render a recommendation request |
For the teaching project, the catalog is bundled with the application. This is important: we do not store live inventory in an MCP session. In a real store, the functions would query a shared inventory database so all deployed instances see consistent stock.
2. The difference between local stdio and remote HTTP
sequenceDiagram
accTitle: Remote shopping tool discovery and inventory call
accDescr: The Python host asks its MCP client to list tools and check inventory; the client sends requests to the remote server and returns the results to the host for Claude.
participant H as Python host
participant C as MCP client
participant S as Remote MCP server
H->>C: list_tools()
C->>S: HTTPS POST /mcp — tools/list
S-->>C: Tool schemas
C-->>H: Tool objects
Note over H: Pass schemas to Claude
H->>C: call_tool(check_inventory, args)
C->>S: HTTPS POST /mcp — tools/call
Note over S: Run Python function
S-->>C: CallToolResult
C-->>H: MCP result
Note over H: Convert result to Claude tool_resultThe MCP client is not the model. The MCP server does not call Claude. When the server finishes a tool, its response goes back through the client to the host application, which decides what to send to Claude next.
Why the 2026 protocol is easier to scale
Modern MCP requests are stateless at the protocol layer: they don't require a mandatory initialize handshake or a sticky Mcp-Session-Id. A load balancer can dispatch independent requests to different healthy server instances. If a workflow needs a shared cart, mint a cart_id and store the cart in a separate database; pass the identifier explicitly in subsequent calls.
That does not mean the shopping application forgets its data, and it does not remove Claude's application-maintained messages history.
For our request/response tools we set stateless_http=True and json_response=True. A streaming or multi-round-trip workflow might need a different response mode; don't copy those settings blindly into a server that relies on in-flight progress or backchannel requests.
3. Where should we deploy: Cloudflare or AWS?
Both work. They optimize for different constraints.
| Decision | Cloudflare Workers | AWS App Runner |
|---|---|---|
| Keep our Python functions unchanged | No, use a TypeScript Worker rewrite or a different Cloudflare runtime | Yes |
| Runtime | Workers isolates | Managed Python container |
| Current MCP transport | Streamable HTTP | Streamable HTTP |
| Capacity control | Cloudflare per-invocation limits; scale by Workers platform | Instance size, minimum/maximum instances, concurrency target |
| Persistent product data | D1 / KV / Durable Objects | DynamoDB / RDS / other shared storage |
| Recommended when | You want very lightweight global tools and already use Cloudflare | You want minimal code changes from the tutorial |
For this article, AWS is the main walkthrough because it reuses our existing Python source. Cloudflare is a complete second implementation in TypeScript, included in the project. The platforms are deployment alternatives, not two required layers in one deployment.
4. AWS walkthrough: deploy the Python shopping server
Step 1 — Preserve tools/resources/prompts; change the transport
At the bottom of shopping_server.py:
if __name__ == "__main__":
mcp.run(
transport="streamable-http",
host="0.0.0.0",
port=int(os.getenv("PORT", "8080")),
streamable_http_path="/mcp",
stateless_http=True,
json_response=True,
)0.0.0.0 is essential in a container so the server listens beyond the container's loopback interface. PORT lets the deployment platform choose the listening port.
The complete server below includes all the previously built capabilities:
"""Stackfable shopping MCP server: tools, resources and prompts over HTTP."""
import json
import os
from pathlib import Path
from mcp.server import MCPServer
mcp = MCPServer("stackfable-shop", version="1.0.0")
CATALOG = Path(__file__).with_name("products.json")
def load_products() -> list[dict]:
return json.loads(CATALOG.read_text(encoding="utf-8"))
@mcp.tool()
def search_products(query: str, max_price: float) -> list[dict]:
"""Search products matching all keywords up to a maximum USD price. Stock is omitted."""
words = query.lower().split()
results = []
for product in load_products():
searchable = f"{product['name']} {product['category']} " + (
"wireless" if product["wireless"] else "wired"
)
if product["price"] <= max_price and all(word in searchable.lower() for word in words):
results.append({key: product[key] for key in ("id", "name", "price", "wireless")})
return results
@mcp.tool()
def check_inventory(product_id: str) -> dict:
"""Check current stock of one known product ID."""
for product in load_products():
if product["id"] == product_id:
return {"product_id": product_id, "in_stock": product["stock"] > 0, "quantity": product["stock"]}
return {"product_id": product_id, "error": "Product not found"}
@mcp.resource("shop://catalog", mime_type="application/json")
def catalog_resource() -> str:
"""Read the product catalog without inventory information."""
return json.dumps([
{key: product[key] for key in ("id", "name", "price", "wireless")}
for product in load_products()
])
@mcp.resource("shop://products/{product_id}", mime_type="application/json")
def product_resource(product_id: str) -> str:
"""Read public details for a product."""
for product in load_products():
if product["id"] == product_id:
return json.dumps({key: product[key] for key in ("id", "name", "category", "price", "wireless")})
return json.dumps({"error": "Product not found", "product_id": product_id})
@mcp.prompt()
def recommend_keyboard(max_price: str = "100", preference: str = "wireless") -> str:
"""Generate an instruction to find and verify a keyboard recommendation."""
return (
f"Find a {preference} mechanical keyboard under ${max_price}. "
"Search our catalog and check inventory for the best match. "
"Do not invent stock or prices."
)
if __name__ == "__main__":
mcp.run(
transport="streamable-http",
host="0.0.0.0",
port=int(os.getenv("PORT", "8080")),
streamable_http_path="/mcp",
stateless_http=True,
json_response=True,
)Step 2 — Package it as a Docker container
Use these files in the aws-python/ directory:
requirements.txt
mcp>=2,<3For a publication or production build, resolve and commit a lockfile to exact tested dependency versions; the range above keeps the learning example on SDK v2.
Dockerfile
FROM python:3.12-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PORT=8080
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY shopping_server.py products.json ./
EXPOSE 8080
USER 10001
CMD ["python", "shopping_server.py"]Build and test locally:
cd aws-python
docker build -t stackfable-shop-mcp:local .
docker run --rm -p 8080:8080 stackfable-shop-mcp:localYour MCP endpoint is now http://localhost:8080/mcp. Do not use your browser opening the URL as a readiness test: MCP expects protocol messages, not a normal webpage. Run the Inspector or the companion MCP client instead.
Step 3 — Publish the image to Amazon ECR
With the AWS CLI configured and Docker running (replace the sample values):
export AWS_REGION=us-west-2
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REPO=stackfable-shop-mcp
aws ecr create-repository --repository-name "$REPO" --region "$AWS_REGION"
aws ecr get-login-password --region "$AWS_REGION" | \
docker login --username AWS --password-stdin "$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com"
docker tag stackfable-shop-mcp:local "$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO:latest"
docker push "$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$REPO:latest"If your repository already exists, skip create-repository. For reproducible deployments, prefer immutable image tags or digests instead of continuously reusing latest.
Step 4 — Create an AWS App Runner service
In the AWS App Runner console: create a container-image service, choose Amazon ECR, select the pushed image, and authorize App Runner to read that private ECR repository using an appropriate access role. Configure:
- Container port:
8080 - Health check:
TCP(the default); a plain HTTP GET/is not an MCP health check - CPU/memory: start small and measure
- Auto scaling: conservative minimum/maximum capacity and concurrency values
App Runner provides an HTTPS service URL. Your MCP URL becomes:
https://YOUR-SERVICE.REGION.awsapprunner.com/mcpThe specific hostname comes from your deployed service; the example above isn't a real address. For public examples, isolate the service from private data; for production, secure the endpoint with a supported authorization architecture before exposing privileged tools.
Why TCP health checks? App Runner defaults to TCP. Our MCP server does not define a normal website homepage returning 200 for GET /, so copying a generic HTTP homepage health check can incorrectly mark the service unhealthy.
5. Cloudflare walkthrough: deploy a stateless MCP Worker
Cloudflare Workers is attractive when a small catalog lookup or lightweight API orchestration fits the Workers runtime. We do not run the existing Python MCPServer source inside a standard JavaScript Worker. Instead, we port the same tool contracts into TypeScript using the MCP TypeScript SDK v2 and Cloudflare's current createMcpHandler.
Step 1 — Scaffold the maintained Worker template
npm create cloudflare@latest -- stackfable-shop --template=cloudflare/ai/demos/remote-mcp-authless
cd stackfable-shopUse the starter's generated package.json and Wrangler settings. Replace its src/index.ts with the provided Cloudflare companion file. The code begins:
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/server";
import { createMcpHandler } from "agents/mcp/server";
import { z } from "zod";
function createServer() {
const server = new McpServer({ name: "stackfable-shop", version: "1.0.0" });
// registerTool, registerResource, registerPrompt ...
return server;
}
const handler = createMcpHandler(createServer);
export default { fetch(request, env, ctx) { return handler(request, env, ctx); } };The complete implementation is in cloudflare-worker/src/index.ts. It registers the same two tools, catalog resource, product resource template, and recommendation prompt. The current SDK v2 uses registerTool, registerResource, and registerPrompt rather than older registration shortcuts.
Step 2 — Test locally and deploy
npm start
# In another terminal:
npx @modelcontextprotocol/inspector@latestIn Inspector choose Streamable HTTP, enter the local /mcp URL shown by Wrangler (the official example uses http://localhost:8788/mcp), and click Connect.
After confirming the tools work:
npx wrangler@latest deployUse the deployed URL, shaped like:
https://stackfable-shop.YOUR-SUBDOMAIN.workers.dev/mcpThe official Cloudflare starter is unauthenticated. That is suitable only for this intentionally public, read-only sample. For real catalog inventory, customer records, or write operations, use Cloudflare's authenticated remote MCP template, OAuth, authorization checks, rate limiting, and tool-level permissions.
Our bundled TypeScript catalog is static. For updates shared across requests, use D1 or another supported external data binding; don't keep mutable business state only in a Worker global.
6. Test the server with MCP Inspector
The same Inspector workflow works for local Docker, deployed AWS, or deployed Cloudflare.
npx @modelcontextprotocol/inspector@latestIn the Inspector UI:
- Select Streamable HTTP (not the legacy SSE transport).
- Enter
http://localhost:8080/mcpor your real deployedhttps://.../mcpURL. - Click Connect.
- Open Tools → List Tools and run
search_productswith{"query":"wireless mechanical keyboard","max_price":100}. - Run
check_inventorywith{"product_id":"kb-101"}. - Open Resources and read
shop://catalogorshop://products/kb-101. - Open Prompts, retrieve
recommend_keyboardusingmax_price=100andpreference=wireless.
Expected demo values: one wireless keyboard at $79 and 8 units in stock. The Inspector's exact control labels may evolve with its version. The endpoint isn't meant to return a human-readable page when opened directly in a normal browser.
Programmatic smoke test (no Claude API required)
With MCP Python SDK v2 installed, run:
python -m pip install 'mcp>=2,<3'
python inspect_remote.py https://YOUR-DEPLOYED-HOST/mcpOur inspect_remote.py uses Client(url), which selects Streamable HTTP, and exercises tools, resource reading, and prompt retrieval. A Claude host can then replace its old StdioServerParameters(...) with Client(url) while preserving the model/tool loop.
7. Capacity planning: how many MCP servers do we need?
First, plan for MCP requests, not user chats and not LLM tokens. One chat may discover tools and make several tools/call requests. The host's Claude API requests are separate network operations and are normally billed and scaled by the LLM provider, not by your MCP server.
Step A — Estimate traffic
Let:
U= active users per dayC= shopping conversations per user per dayT= average MCP tool calls per conversationD= resource/prompt/discovery calls per conversation (account for caching)P= ratio of peak requests/second to average requests/second
Then approximate:
MCP requests/day ≈ U × C × (T + D)
Average requests/sec ≈ MCP requests/day / 86,400
Peak requests/sec ≈ Average requests/sec × PExample (invented workload): 5,000 active users, one shopping conversation each, three tool calls and one other MCP call per conversation, peak traffic ten times the daily average:
Daily MCP requests = 5,000 × 1 × 4 = 20,000
Average RPS = 20,000 / 86,400 ≈ 0.23
Peak RPS = 0.23 × 10 ≈ 2.3A modest stateless server may easily handle this workload; but this request-count estimate does not tell us whether each tool call spends 2 ms in memory, 300 ms waiting on a database, or 30 seconds calling an external API.
Step B — Convert traffic into concurrency
Using Little's Law as a first approximation:
In-flight requests ≈ Arrival rate (RPS) × Average response time (seconds)Suppose your measured peak is 30 RPS and a typical request is 0.2 seconds:
In-flight concurrency ≈ 30 × 0.2 = 6If your intended utilization ceiling is 60%, the rough capacity target is:
Required aggregate safe concurrency ≈ 6 / 0.60 = 10Add headroom for bursts and a failure of one replica. This is not a guarantee that 10 Python requests are simultaneously CPU-efficient. For CPU-bound Python code, benchmark actual throughput; for mostly waiting-on-I/O tools, asynchronous execution often helps.
Step C — Benchmark one replica
Measure your deployed tool server under realistic tool payloads. Track:
| Metric | Why it matters |
|---|---|
MCP tools/call RPS per tool | Which operations dominate traffic |
| p50 / p95 / p99 latency | User-perceived tail latency |
| Active in-flight calls | Peak parallel work |
| CPU utilization / CPU time | Compute bottlenecks and Worker charges |
| Memory / peak memory | Instance sizing and request bursts |
| Error rate, timeouts, 429s | Overload and throttling |
| Database and downstream latency | Bottlenecks outside the MCP server |
For a concrete load test, benchmark the MCP operations, not repeated GETs to /mcp. Use a client that sends valid MCP requests, and vary concurrent tools/call traffic until latency or errors exceed your targets. Record a measured safe concurrent requests per instance or safe sustainable RPS per instance at your latency goal.
Step D — Choose scaling policy by platform
AWS App Runner: Configure MaxConcurrency, MinSize, and MaxSize. If a load test shows one instance handles 20 concurrent requests safely, consider a lower target such as 10–15 to leave room for bursts, then choose a maximum number of instances based on peak load and budget. App Runner scales based on concurrent requests; CPU and memory allocations still affect what one instance can safely process. For larger systems, ECS/Fargate allows more detailed CPU/memory and request-count scaling policies.
Cloudflare Workers: You generally don't choose the number of replicas. Capacity planning revolves around per-request CPU and memory limits, request quotas, subrequests to databases/APIs, latency, and downstream service limits. The current Workers Paid plan includes 10 million requests/month and 30 million CPU-ms/month, with usage-based charges afterward; these are billing allotments, not guaranteed throughput targets. Always check current plan pricing and limits before publishing estimates.
Step E — Remember downstream bottlenecks and abuse
An MCP tool that calls a database or retailer API may hit downstream rate limits before saturating the server CPU. Limit concurrent calls, set timeouts, cache safe read results, and use exponential backoff for temporary failures. Apply authentication and rate limits before exposing costly or write-enabled tools. A public, unauthenticated MCP endpoint can otherwise be scraped or used to run up usage costs.
flowchart TD
accTitle: MCP capacity planning loop
accDescr: Estimate calls, measure peak traffic and tool performance, load test, then optimize or set scaling limits according to latency and errors.
A[Estimate MCP calls from real conversations] --> B[Measure peak requests per second]
B --> C[Measure latency / CPU / memory per tool]
C --> D[Load test one instance or Worker]
D --> E{Target p95 and error budget met?}
E -->|No| F[Optimize code and downstream calls]
F --> D
E -->|Yes| G[Set scaling limits, monitoring, and budget alerts]8. Production readiness checklist
Before giving the remote /mcp URL to outside users, make sure you have:
- Authorization: OAuth or another appropriate MCP-compatible scheme, scoped to tools and user permissions. In this tutorial, the public endpoints are deliberately limited to fictional read-only data.
- Transport security: HTTPS on the deployed endpoint; do not ship credentials in source files.
- Request controls: schema validation, reasonable input-size limits, per-tool timeouts, rate limits, and concurrency limits.
- Data controls: persistent data outside ephemeral containers/isolate globals, appropriate tenant isolation, and no secrets in resource payloads.
- Observability: MCP method/name, request/trace ID, outcome, latency, and tool-specific failure rates; avoid logging sensitive arguments.
- Cost controls: provider budgets, max scaling limits, downstream quotas, and a way to disable a costly tool quickly.
- Versioning: pinned dependencies and repeatable deployments; test discovery, tools, resources, and prompts after every deployment.
9. What we've learned across the series
Part 1 — Claude requests a tool; Python runs it
Part 2 — Wrap those functions in an MCP server
Part 3 — Build an MCP client; translate Claude requests to MCP
Part 4 — Discover and route tools across multiple MCP servers
Part 5 — Add resources and reusable prompts
Part 6 — Replace local stdio with remote Streamable HTTP,
deploy the server, inspect it, and plan its capacityOur final mental model:
Claude decides what to request. The host manages the conversation. The MCP client carries standardized requests to a local or remote MCP server. The server runs the operation. Deployment and scaling change where that operation runs—not how the tool-calling loop works.
Knowledge check
Official references
- MCP Python SDK v2 — Running a server
- MCP Python SDK v2 — Remote client
- MCP specification 2026-07-28
- Cloudflare — Build a remote MCP server
- Cloudflare — Workers pricing
- AWS App Runner — Container image services
- AWS App Runner — Scaling
The lesson transcript supplied by the reader provides the original progression (remote transport → MCP Inspector → deployment). The modern transport, Cloudflare/AWS implementation, deployment guidance, and capacity model were added through current documentation and original examples. The scripts are teaching examples; no cloud deployment has been performed as part of this article.