Remote MCP Server over HTTP with Authentication in Python

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 8 min read🎯 D8 MCP Server Development and Integration · D7 API Key and Credential Handling

👋 In plain words: A stdio server runs on one person’s machine. To share an MCP server with a whole team, it has to run over the network, and then it must check who is calling. This lesson moves a server to HTTP and adds token checking, one step at a time, then lists what to harden before production.

Advertisement

Remote MCP servers let every developer, bot and agent use one integration, but they also expose your systems over the network. In this lesson you will run a Python MCP server over Streamable HTTP, protect it with a bearer-token verifier and required scopes, connect an authenticated client, watch an unauthenticated call get rejected with 401, and walk through the production checklist: OAuth, audience checks, HTTPS, least privilege and secrets.

📖 What You’ll Learn: You will be able to serve an MCP server over Streamable HTTP, enforce bearer-token authentication and scopes with the Python SDK, connect an authenticated client, and harden a remote server for production.

🔑 Key terms

  • Streamable HTTP: MCP’s HTTP transport; clients send JSON-RPC messages by POST and can receive streamed responses.
  • Bearer token: an access token sent in the Authorization: Bearer <token> header.
  • Scope: a named permission inside a token, such as qa:read.
  • Resource server: the server that holds the protected data and validates tokens (your MCP server).
  • Authorization server: the system that issues tokens (for example your company’s identity provider).

🪜 Step 1: Decide what needs protecting

Before writing code, list who calls the server and what they may do. For a QA results server:

Caller Needs Scope
Claude Code on developer laptops Read results qa:read
Nightly triage agent Read results, add comments qa:read, qa:comment
Nobody Delete runs (no tool exposed)

Least privilege starts here: tools you do not expose cannot be misused, even by a prompt-injected agent.

🪜 Step 2: Write a token verifier

The Python SDK asks you for an object with an async verify_token() method. It returns an AccessToken (with scopes) for a valid token and None otherwise. This one uses a static table for the demo; in production you would validate a JWT or call your identity provider’s introspection endpoint:

📄 auth.py

import os

from mcp.server.auth.provider import AccessToken

RESOURCE = "http://127.0.0.1:8811/mcp"
# demo only: tokens come from an environment variable, never from code in production
TOKENS = {os.environ.get("QA_MCP_TOKEN", "dev-token-123"): ("claude-code-laptop", ["qa:read"])}


class StaticTokenVerifier:
    async def verify_token(self, token: str) -> AccessToken | None:
        entry = TOKENS.get(token)
        if entry is None:
            return None  # unknown token -> 401
        client_id, scopes = entry
        return AccessToken(token=token, client_id=client_id, scopes=scopes, resource=RESOURCE)
Advertisement

🪜 Step 3: Serve over Streamable HTTP with auth

Pass the verifier and AuthSettings to MCPServer, then run the streamable-http transport:

📄 http_server.py

from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver import MCPServer

from auth import RESOURCE, StaticTokenVerifier

mcp = MCPServer(
    "qa-results-remote",
    token_verifier=StaticTokenVerifier(),
    auth=AuthSettings(
        issuer_url="https://auth.example.com",   # who issues tokens (your identity provider)
        resource_server_url=RESOURCE,            # this server
        required_scopes=["qa:read"],             # every caller needs at least this
    ),
)


@mcp.tool()
def get_failed_tests(build: str) -> list[str]:
    """List the failed tests of a CI build. build is the numeric build number, e.g. 812."""
    return ["test_checkout_total"] if build == "812" else []


if __name__ == "__main__":
    mcp.run("streamable-http", host="127.0.0.1", port=8811)
  • required_scopes is checked for every request, before any tool runs.
  • issuer_url and resource_server_url are also published as metadata, so OAuth-capable clients can discover where to get a token for this server.

🪜 Step 4: Connect an authenticated client

The client sends the token in a header. The script starts the server, waits until it listens, makes one call with a valid token and one with a wrong token, then stops the server:

📄 http_client.py

import asyncio
import socket
import subprocess
import sys
import time

from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from mcp.shared._httpx_utils import create_mcp_http_client

URL = "http://127.0.0.1:8811/mcp"


def wait_for_port(port: int, timeout: float = 15) -> None:
    end = time.time() + timeout
    while time.time() < end:
        with socket.socket() as s:
            if s.connect_ex(("127.0.0.1", port)) == 0:
                return
        time.sleep(0.2)
    raise RuntimeError("server did not start")


async def call(token: str) -> None:
    http = create_mcp_http_client(headers={"Authorization": f"Bearer {token}"})
    try:
        async with Client(streamable_http_client(URL, http_client=http)) as client:
            result = await client.call_tool("get_failed_tests", {"build": "812"})
            print(f"token {token!r}: {result.structured_content}")
    except Exception as e:  # the 401 surfaces as a connection failure
        print(f"token {token!r}: rejected ({type(e).__name__})")


server = subprocess.Popen([sys.executable, "http_server.py"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
    wait_for_port(8811)
    asyncio.run(call("dev-token-123"))
    asyncio.run(call("stolen-or-wrong-token"))
finally:
    server.terminate()
    server.wait()

⌨️ Terminal

python http_client.py

🖥️ Output

token 'dev-token-123': {'result': ['test_checkout_total']}
token 'stolen-or-wrong-token': rejected (ExceptionGroup)

The server log for the second call shows 401 Unauthorized: the request never reached the tool.

⚠️ Watch out: create_mcp_http_client(headers=...) keeps the token in memory, which is fine. Never put tokens in the URL (?token=...): URLs end up in proxy logs, browser history and error reports.
Advertisement

🪜 Step 5: Check scopes per tool

required_scopes applies to every request. For finer control, check the caller’s scopes inside a tool that changes data. In the SDK, request context gives you the authenticated principal; the simplest robust pattern is to keep separate servers or separate tokens for read and write access, so a read-only token can never reach write tools. Combine that with the approval patterns from Lesson 24 for risky actions.

🪜 Step 6: Harden for production

Use this checklist before exposing a remote MCP server:

  1. Real tokens from a real issuer. MCP authorization for HTTP builds on OAuth 2.1. Let your identity provider issue short-lived tokens; validate signature, expiry and audience (the token must be issued for this server, not just any service). The SDK’s AuthSettings has options to enforce the token’s resource.
  2. HTTPS only, behind your normal gateway or ingress. Never plain HTTP outside localhost.
  3. Least privilege. Expose only the tools needed; separate read and write; give each client its own credentials so you can revoke one without the others.
  4. Secrets server-side. The server holds the credentials for Jira, the database or CI. Clients and the model never see them; they only see tool results.
  5. Validate inputs and shape outputs (Lessons 24 and 27). Treat tool arguments as untrusted, because they come from a model that may have read malicious content.
  6. Log and monitor: who called which tool, with which arguments, and the result status. Alert on unusual volume.
🎯 Exam focus: Expect scenarios such as “an MCP server is exposed over HTTP with a shared static key embedded in every client” or “tokens are accepted without checking which service they were issued for”. The fixes are per-client, short-lived, audience-checked tokens; server-side secrets; least-privilege tool sets; and HTTPS.

🌍 Real-world example: Ravi’s shared server

Ravi first deployed the team’s MCP server with one shared token pasted into everyone’s Claude Code config. When a contractor left, rotating the token broke 30 laptops at once. The platform team moved the server behind the company’s identity provider: each developer now signs in, gets a short-lived token with qa:read, and the nightly agent uses its own service identity with qa:comment.

Advertisement

🧪 Practice Questions

Question 1. A remote MCP server accepts any valid token issued by the company’s identity provider, including tokens issued for unrelated internal services. What is missing?

  • A. A larger timeout
  • B. Audience (resource) validation: the token must be issued for this MCP server
  • C. stdio transport
  • D. A shorter tool description
Show answer

Answer: B. Without an audience check, a token stolen from or issued to another service can be replayed against this server.

Question 2. Which transport should a team use for an MCP server shared by 50 developers and two automated agents?

  • A. stdio, copied to every laptop
  • B. Streamable HTTP with authentication
  • C. Message Batches
  • D. A resource template
Show answer

Answer: B. A shared, remote server needs a network transport and authentication; stdio is for local, single-user servers.

Question 3. Which two practices reduce damage if an agent using a remote MCP server is prompt-injected? (Choose 2.)

  • A. Expose only the tools the agent needs, with read-only tokens where possible
  • B. Put the database password in the tool description so the agent can connect directly
  • C. Keep backend credentials on the server so the model never sees them
  • D. Disable authentication for internal networks
Show answer

Answer: A and C. Least privilege limits what injected instructions can do, and server-side secrets keep credentials out of the model’s reach.

Question 4. How should a client send its MCP access token?

  • A. In the Authorization: Bearer header
  • B. As a query parameter in the URL
  • C. Inside the tool arguments
  • D. In the system prompt
Show answer

Answer: A. Headers keep tokens out of URLs and logs, and out of the model’s context.

📝 Assignment

  1. Task 1: Run http_client.py and then change required_scopes to ["qa:write"].
    ✅ Done when: the valid token is now rejected too, and you can explain why.
  2. Task 2: Read your token table from an environment variable or a file outside the repo instead of code.
    ✅ Done when: no token appears in any committed file.
  3. Stretch: Replace StaticTokenVerifier with one that validates a signed JWT (for example with the PyJWT library) and checks issuer, expiry and audience.
    ✅ Done when: an expired token and a token with the wrong audience are both rejected.
Advertisement

❓ Frequently Asked Questions

🤔 How do I secure a remote MCP server?

Use HTTPS, require tokens from your identity provider (OAuth 2.1 based), validate expiry and audience, enforce scopes, expose only needed tools, and keep backend secrets on the server.

🤔 What is Streamable HTTP in MCP?

The HTTP transport for MCP: clients POST JSON-RPC messages to one endpoint and can receive streamed responses, which suits remote and shared servers.

🤔 Can I use API keys instead of OAuth for MCP?

For internal prototypes, a static bearer token per client works, as in this lesson. For production and shared servers, short-lived tokens from an identity provider are safer and easier to revoke.

🤔 Where should credentials for Jira or a database live?

On the MCP server, in a secrets manager or environment. Clients and the model should only ever see tool results.

🏁 Summary

  • Serve shared MCP servers over Streamable HTTP with mcp.run("streamable-http", ...).
  • Validate bearer tokens with a TokenVerifier and enforce required_scopes via AuthSettings.
  • Clients send tokens in the Authorization header, never in URLs.
  • Production: OAuth-issued short-lived tokens, audience checks, HTTPS, least privilege, server-side secrets, logging.
📝 Test yourself: D8 Tools and MCP practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Connect an MCP Server to the Claude API and Claude Code.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.