MCP: From Motivation to DeploymentLesson 07

Deploy a Remote MCP Server: Streamable HTTP, Cloudflare, AWS, and Capacity Planning

Move a shopping MCP server from local stdio to remote HTTP, compare deployment options, and estimate the capacity it needs.

Shopping inventory call through a remote MCP server1 · Shoppinghost2 · MCPclient3 · Remoteserver4 · ProductcatalogHTTPS /mcp

Navigate

On this page

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:

PYTHON
# 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:

PYTHON
# 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.

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 capabilityName or URIPurpose
Toolsearch_products(query, max_price)Match catalog products without stock
Toolcheck_inventory(product_id)Look up quantity
Resourceshop://catalogRead a catalog snapshot
Resource templateshop://products/{product_id}Read one product's public details
Promptrecommend_keyboardRender 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

The 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.

DecisionCloudflare WorkersAWS App Runner
Keep our Python functions unchangedNo, use a TypeScript Worker rewrite or a different Cloudflare runtimeYes
RuntimeWorkers isolatesManaged Python container
Current MCP transportStreamable HTTPStreamable HTTP
Capacity controlCloudflare per-invocation limits; scale by Workers platformInstance size, minimum/maximum instances, concurrency target
Persistent product dataD1 / KV / Durable ObjectsDynamoDB / RDS / other shared storage
Recommended whenYou want very lightweight global tools and already use CloudflareYou 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:

PYTHON
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:

PYTHON
"""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

TEXT
mcp>=2,<3

For 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

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:

BASH
cd aws-python
docker build -t stackfable-shop-mcp:local .
docker run --rm -p 8080:8080 stackfable-shop-mcp:local

Your 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):

BASH
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:

TEXT
https://YOUR-SERVICE.REGION.awsapprunner.com/mcp

The 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

BASH
npm create cloudflare@latest -- stackfable-shop --template=cloudflare/ai/demos/remote-mcp-authless
cd stackfable-shop

Use the starter's generated package.json and Wrangler settings. Replace its src/index.ts with the provided Cloudflare companion file. The code begins:

TYPESCRIPT
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

BASH
npm start
# In another terminal:
npx @modelcontextprotocol/inspector@latest

In 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:

BASH
npx wrangler@latest deploy

Use the deployed URL, shaped like:

TEXT
https://stackfable-shop.YOUR-SUBDOMAIN.workers.dev/mcp

The 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.

BASH
npx @modelcontextprotocol/inspector@latest

In the Inspector UI:

  1. Select Streamable HTTP (not the legacy SSE transport).
  2. Enter http://localhost:8080/mcp or your real deployed https://.../mcp URL.
  3. Click Connect.
  4. Open Tools → List Tools and run search_products with {"query":"wireless mechanical keyboard","max_price":100}.
  5. Run check_inventory with {"product_id":"kb-101"}.
  6. Open Resources and read shop://catalog or shop://products/kb-101.
  7. Open Prompts, retrieve recommend_keyboard using max_price=100 and preference=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:

BASH
python -m pip install 'mcp>=2,<3'
python inspect_remote.py https://YOUR-DEPLOYED-HOST/mcp

Our 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 day
  • C = shopping conversations per user per day
  • T = average MCP tool calls per conversation
  • D = resource/prompt/discovery calls per conversation (account for caching)
  • P = ratio of peak requests/second to average requests/second

Then approximate:

TEXT
MCP requests/day ≈ U × C × (T + D)
Average requests/sec ≈ MCP requests/day / 86,400
Peak requests/sec ≈ Average requests/sec × P

Example (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:

TEXT
Daily MCP requests = 5,000 × 1 × 4 = 20,000
Average RPS        = 20,000 / 86,400 ≈ 0.23
Peak RPS           = 0.23 × 10 ≈ 2.3

A 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:

TEXT
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:

TEXT
In-flight concurrency ≈ 30 × 0.2 = 6

If your intended utilization ceiling is 60%, the rough capacity target is:

TEXT
Required aggregate safe concurrency ≈ 6 / 0.60 = 10

Add 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:

MetricWhy it matters
MCP tools/call RPS per toolWhich operations dominate traffic
p50 / p95 / p99 latencyUser-perceived tail latency
Active in-flight callsPeak parallel work
CPU utilization / CPU timeCompute bottlenecks and Worker charges
Memory / peak memoryInstance sizing and request bursts
Error rate, timeouts, 429sOverload and throttling
Database and downstream latencyBottlenecks 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.

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

TEXT
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 capacity

Our 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

Another application needs to check stock for kb-101 through the shopping server. Which change makes the existing Python tools reachable without moving the Claude conversation into the server?
The shopping service is scaled to multiple instances, and a cart must survive requests that reach different instances. Where should the cart live?
The host serves 5,000 shopping conversations a day and calls check_inventory three times in each. Why is that count alone insufficient to choose the App Runner instance limit?

Official references

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.

Related Posts

Product resource selected by the shopping host1 · Shopperchooses ID2 · Pythonhost3 · Productresource4 · Displayonly5 · Claudegets context

MCP Beyond Tools: Add Resources and Prompts to Our Shopping Assistant

  • Stackfable
  • 08 Nov 2026

Extend a shopping MCP server with product resources and a reusable prompt, and see when the host passes each to Claude.

Read More: MCP Beyond Tools: Add Resources and Prompts to Our Shopping Assistant
A shopping request routed to two MCP servers1 · Keyboardrequest2 · Pythonhost3 · Shopsearch + stock4 · Notessave file

Connecting One MCP Client to Multiple Servers: Build a Shopping Assistant That Can Save Notes

  • Stackfable
  • 08 Nov 2026

Connect a shopping assistant to separate shopping and filesystem MCP servers, then discover and route their tools through one Python host.

Read More: Connecting One MCP Client to Multiple Servers: Build a Shopping Assistant That Can Save Notes
Shopping tool request through an MCP client1 · Clauderequest2 · Pythonhost3 · MCPclient4 · Shopserver5 · result to Claude

From MCP Server to MCP Client: Connect Our Shopping Assistant to Claude

  • Stackfable
  • 08 Nov 2026

Connect a shopping MCP server to Claude by discovering tools, routing tool calls, and returning results through a Python host.

Read More: From MCP Server to MCP Client: Connect Our Shopping Assistant to Claude