Simple HTTP MCP Server Implementation
This project provides a lightweight server implementation for the Model Context Protocol (MCP) over HTTP. It allows you to expose Python functions as tools and prompts that can be discovered and executed remotely via a JSON-RPC interface. It is intended to be used with a Starlette or FastAPI application (see demo).
Table of Contents
- Features
- Installation
- Server Architecture
- Protocol Version
- Tools
- Server State Management
- Request Access
- Prompts
- STDIO Transport
- Authentication and Authorization
- OAuth 2.1 Authorization (auth_mcp)
- API Reference
- Security Surfaces by Endpoint
- License
Features
- MCP Protocol Compliant: Implements the MCP specification for tool and prompts discovery and execution. No support for notifications.
- One Protocol Revision: Speaks the stateless
2026-07-28revision only —server/discover, per-request_meta, no handshake, no session. A single dispatch path means a request cannot select weaker handling by declaring an older revision. - HTTP and STDIO Transport: Uses HTTP (POST requests) or STDIO for communication.
- Async Support: Built on
StarletteorFastAPIfor asynchronous request handling. - Type-Safe: Leverages
Pydanticfor robust data validation and serialization. - Server State Management: Access shared state through the lifespan context
using the
get_state_keymethod. - Request Access: Access the incoming request object from your tools and prompts.
- Authorization Scopes: Support for scope-based authorization using Starlette's authentication system.
- Error Handling: Tools can optionally return error messages instead of raising exceptions.
- OAuth 2.1 Authorization: Optional
auth_mcppackage with Bearer token validation, Protected Resource Metadata (RFC 9728), andWWW-Authenticateerror responses. Install withpip install http-mcp[auth].
Server Architecture
The library provides a single MCPServer class that uses lifespan to manage
shared state across the entire application lifecycle.
MCPServer
The MCPServer is designed to work with Starlette's lifespan system for
managing shared server state.
Key Characteristics:
- Lifespan Based: Uses Starlette's lifespan events to initialize and manage shared server state
- Application-Level State: State persists across the entire application lifecycle, not per-request
- Flexible: Can be used with any custom context class stored in the lifespan state
Constructor Parameters:
name(str): The name of your MCP serverversion(str): The version of your MCP servertools(tuple[Tool, ...]): Tuple of tools to expose (default: empty tuple)prompts(tuple[Prompt, ...]): Tuple of prompts to expose (default: empty tuple)instructions(str | None): Optional instructions for AI assistants on how to use this servercache_ttl_ms(int): Freshness hint in milliseconds sent withtools/list,prompts/list, andserver/discoverresults (default:300000). Use0to tell clients never to cache. See Caching Hints.cache_scope("public" | "private" | None): Whether shared caches may reuse those results across authorization contexts. Derived automatically when omitted. See Caching Hints.allowed_origins(tuple[str, ...]): Origins the HTTP transport accepts (default: empty, meaning only loopback origins are accepted). See Origin Validation.require_origin(bool): Whether a request carrying noOriginheader at all is refused whenallowed_originsis set (default:False). See Origin Validation.
Example Usage:
import contextlib
from collections.abc import AsyncIterator
from typing import TypedDict
from dataclasses import dataclass, field
from starlette.applications import Starlette
from http_mcp.server import MCPServer
@dataclass
class Context:
call_count: int = 0
user_preferences: dict = field(default_factory=dict)
class State(TypedDict):
context: Context
@contextlib.asynccontextmanager
async def lifespan(_app: Starlette) -> AsyncIterator[State]:
yield {"context": Context()}
mcp_server = MCPServer(
name="my-server",
version="1.0.0",
tools=my_tools,
prompts=my_prompts,
instructions="Optional instructions for AI assistants on how to use this server"
)
app = Starlette(lifespan=lifespan)
app.mount("/mcp", mcp_server.app)
Protocol Version
The server implements exactly one protocol revision, 2026-07-28, and every
request travels the same path. There is no version negotiation and no second set
of rules a request can select into.
Breaking change in 0.17.0. Support for the session-based revisions
2025-11-25,2025-06-18, and2025-03-26was removed, along withinitialize,notifications/initialized, andping. A client that speaks only those revisions can no longer talk to this server. Serving one revision is also what makes the request-metadata headers below trustworthy: while two eras coexisted, a request could skip the header checks by declaring the older one, so an intermediary routing onMcp-Methodcould be desynchronised from the server acting on the body.
Breaking change in 0.18.0.
ServerInterface.get_tool_input_schemanow takes theRequest, so authorization scopes are honoured before dispatch; implementations of the interface must update, whileMCPServerusers are unaffected. MirroredMcp-Param-*values are compared textually rather than numerically, so a header reading3.0for"replicas": 3now gets-32020. Notification handling was subsequently corrected as described below.
Breaking changes in 0.19.0rc1.
ProtectedResourceMetadata.authorization_serversnow contains validated issuer strings instead ofAnyHttpUrlobjects.AuthorizationServerMetadata.issueris also a string. This preserves issuer spelling exactly, including trailing slashes, case and explicit ports. Pass strings when constructing metadata; migrate existing URL objects withstr(url). Useurllib.parse.urlsplit(issuer)instead of URL-object properties such as.hostor.path. Other metadata URL fields retainAnyHttpUrl.Tool.annotationsis aToolAnnotationsmodel; unspecified safety hints are omitted. Configured structured tool errors now retain their data withisError:true. Direct invocation callers must handleStructuredToolInvocationFailedinstead of a plainErrorMessagesuccess outcome.
Behavior changes in 0.19.0rc2.
ProtectedMCPAppConfig.middlewareswraps only the configured MCP mount, preserving the original scope. Move middleware that should cover OAuth endpoints too tocreate_protected_mcp_app(config, middleware=[...]).- Local HTTP authorization servers can be enabled with
AuthorizationTransportPolicy.ALLOW_LOOPBACK_HTTPas validation context. HTTPS remains the default; only canonical loopback hosts are permitted by the development opt-in.
Tool input schemas use Pydantic's validation aliases. Output schemas use
serialization aliases and serialization mode, including computed fields. Tools
can return object, array, scalar or null values through a Pydantic model;
structuredContent and the JSON text fallback describe the same result.
JSON-RPC requests require a non-null integer or string ID. Malformed envelopes
report -32600, unknown methods report -32601, and invalid parameters report
-32602. A message without an ID is a notification: it never invokes a request
method or receives a JSON-RPC response. HTTP checks the mirrored headers before
accepting it with an empty 202 response; header mismatches get an empty 400
response. STDIO ignores unsupported notifications.
List cursors must be strings issued by this server. Invalid or out-of-range
offsets report -32602; tools support pagination, while prompts are returned in
one page. Unexpected prompt crashes report -32603 rather than a successful
empty prompt. Explicit PromptInvocationError feedback retains its existing
behavior.
Empty tool or prompt registrations leave that capability unadvertised. Its list
and invocation methods then return -32601 (HTTP 404), matching discovery.
Register at least one tool or prompt before using that feature's methods.
Behaviour changes since 0.18.0. These close weaknesses found by an attack review of the transports and of
auth_mcp:
- Without
allowed_origins, a browserOriginthat is not loopback now gets 403 (see Origin Validation). A server reached from browsers elsewhere must list those origins.- A mirrored header (
MCP-Protocol-Version,Mcp-Method,Mcp-Name, or an annotatedMcp-Param-*) sent more than once gets-32020.- A tool whose header-mirrored argument also answers to an alias is refused when the server is constructed.
- JSON-RPC ids must be integers or strings;
trueor1.0are no longer coerced to1. Malformed JSON reports-32700rather than-32602.Arguments.get_state_keyfailures reach the client asInternal server error; the key name is logged instead.- A 403 for missing scopes carries
WWW-Authenticate: Bearer error="insufficient_scope", scope="...".- STDIO: an oversized line no longer ends the session, validation errors echo the request id, the scope names are no longer listed, and anything a tool writes to stdout goes to stderr.
auth_mcp:/registercaps the body while reading (413), checks the media type exactly, refuses redirect URIs with backslashes, whitespace or user information, and accepts only the grant types, response types and auth methods it serves.OAuthAuthenticationBackendrefuses tokens whoseTokenInfo.expires_athas passed or whoseaudiencenames another resource. A 401 to a request without a Bearer token carries noerror.
The 2026-07-28 Request Shape
The revision has no session concept. In practice:
-
No handshake. Every request restates its protocol version and the client's capabilities in
_meta:{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "get_weather", "arguments": { "location": "Seattle, WA" }, "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": { "name": "ExampleClient", "version": "1.0.0" }, "io.modelcontextprotocol/clientCapabilities": {} } } }
protocolVersionandclientCapabilitiesare required; omitting either gets a-32602and HTTP 400. Any other version gets a-32022whosedata.supportedlists the one revision this server speaks. -
server/discoverreplacesinitializefor capability discovery. It reports the supported version, capabilities, instructions, and server identity in one call, and is answered without any prior request:{ "resultType": "complete", "supportedVersions": ["2026-07-28"], "capabilities": { "tools": { "listChanged": false }, "prompts": { "listChanged": false } }, "_meta": { "io.modelcontextprotocol/serverInfo": { "name": "my-server", "version": "1.0.0" } }, "ttlMs": 300000, "cacheScope": "public" }
-
Every result carries
resultType: "complete"and a_metablock naming the server. -
initialize,notifications/initialized,ping, andlogging/setLeveldo not exist, along with the session and SSE resumption machinery. They return-32601with HTTP 404. JSON-RPC notifications — anotifications/*message with noid— still get202 Acceptedand no body, because JSON-RPC forbids responding to them. -
Required request headers. Every POST must send
MCP-Protocol-VersionandMcp-Method, plusMcp-Nameontools/callandprompts/get. Each must match the corresponding body value, or the request is rejected with-32020(HeaderMismatch) and HTTP 400 — this stops a proxy routing on one value while the server acts on another. Values that cannot be expressed as plain ASCII use the=?base64?...?=envelope, which the server decodes before comparing. -
Unknown tools and prompts report
-32602, which is what the tools and prompts specs prescribe.-32002was retired by this revision. -
Mcp-Session-IdandLast-Event-IDare ignored, andGET/DELETEon the MCP endpoint return405 Method Not Allowed.
Multi round-trip requests (elicitation, sampling, roots) and
subscriptions/listen are not implemented: this server exposes no
client-input-dependent features and declares listChanged: false, so neither
applies to it.
Caching Hints
tools/list, prompts/list, and server/discover results carry ttlMs and
cacheScope so clients can avoid re-fetching a list that has not changed:
mcp_server = MCPServer(
name="my-server",
version="1.0.0",
tools=my_tools,
cache_ttl_ms=300_000, # clients may treat the list as fresh for 5 minutes
cache_scope="public", # shared caches may serve it to any caller
)
Tools and prompts are fixed when MCPServer is constructed, so ttlMs really
bounds how long a client may miss a redeploy rather than how long the data is
stable. Set it to 0 to ask clients never to cache.
cache_scope is derived when you omit it: "private" if any tool or prompt is
scope-restricted — the list then varies per caller, so a shared cache must not
reuse it across authorization contexts — and "public" otherwise. Override it
if your deployment knows better. Note that cacheScope governs caching only; it
is never a substitute for the per-tool scope checks.
Origin Validation
Browsers attach an Origin header, which is what lets a server refuse requests
smuggled in by DNS rebinding. A rebinding page points its own hostname at
127.0.0.1 but still sends its own origin, so by default the server accepts
only loopback origins (localhost, 127.0.0.1, [::1], any port, http or
https) and refuses every other one with 403 Forbidden. A local server is
protected without configuration.
A server that browsers on other origins should reach, including a web app served from the server's own public hostname, lists them explicitly:
mcp_server = MCPServer(
name="my-server",
version="1.0.0",
tools=my_tools,
allowed_origins=("https://app.example.com",),
)
A request whose Origin is present and not on the list gets 403 Forbidden;
once a list is set, loopback origins are only accepted if they are on it.
Requests with no Origin at all — ordinary non-browser clients — are unaffected
by default, because browsers always send Origin on a POST and the rebinding
threat model does not cover clients that are not browsers.
If the endpoint should only ever serve browser traffic, add require_origin to
refuse a request that omits the header too, which makes the allowlist mandatory
rather than advisory:
mcp_server = MCPServer(
name="my-server",
version="1.0.0",
tools=my_tools,
allowed_origins=("https://app.example.com",),
require_origin=True,
)
require_origin does nothing on its own — it only tightens an allowlist that is
already configured. When running locally, also bind to 127.0.0.1 rather than
0.0.0.0.
Mirroring Tool Parameters into Headers
A tool can ask clients to copy specific argument values into Mcp-Param-*
headers, so proxies can route or rate-limit on them without parsing the body.
Annotate the field with x-mcp-header:
from pydantic import BaseModel, Field
class ExecuteSQLInput(BaseModel):
region: str = Field(
description="The region to execute the query in",
json_schema_extra={"x-mcp-header": "Region"},
)
query: str = Field(description="The SQL query to execute")
A conforming client then sends Mcp-Param-Region: us-west1 alongside the call,
and the server verifies it against the body — rejecting the request with
-32020 if the header is missing, contradicts the argument, or is sent when the
argument is absent. Mcp-Param-* headers that no annotation claims are ignored,
as intermediaries are expected to forward unrecognised ones untouched.
The comparison is textual, against the value as JSON writes it: for
"replicas": 3 the header must read exactly 3, not 3.0, +3, or 3.
Numeric coercion would call those equal while an intermediary routing on the raw
header string saw something else, which is the desync the mirroring exists to
prevent.
Each mirrored header must be sent once. A repeated MCP-Protocol-Version,
Mcp-Method, Mcp-Name, or annotated Mcp-Param-* line gets -32020 even
when its first copy matches the body, because intermediaries join repeated lines
or keep the last one and would route on a value the server never checked.
Base64-wrapped values (=?base64?...?=) must use the canonical encoding.
Only string, integer, and boolean fields reachable through a plain chain
of object properties can be annotated, and no two fields may claim the same
header name — a collision is refused when the server is constructed, because
keeping one of the two annotations would leave the other silently unenforced. An
annotated field (and every field on its path) must not answer to an alias
(alias, validation_alias, or a model's alias_generator): the header is
compared with the argument under its field name, so an alias would let a request
put one value there for the check and another under the alias for the tool. Such
a tool is refused when the server is constructed. Do not annotate sensitive
values: header contents are visible to every intermediary on the path.
Tools
Tools are the functions that can be called by the client.
Basic Tool Example
- Define the arguments and output for the tools:
# app/tools/models.py
from pydantic import BaseModel, Field
class GreetInput(BaseModel):
question: str = Field(description="The question to answer")
class GreetOutput(BaseModel):
answer: str = Field(description="The answer to the question")
# Note: the description on Field will be passed when listing the tools.
# Having a description is optional, but it's recommended to provide one.
- Define the tools:
# app/tools/tools.py
from http_mcp.types import Arguments
from app.tools.models import GreetInput, GreetOutput
def greet(args: Arguments[GreetInput]) -> GreetOutput:
return GreetOutput(answer=f"Hello, {args.inputs.question}!")
# app/tools/__init__.py
from http_mcp.types import Tool
from app.tools.models import GreetInput, GreetOutput
from app.tools.tools import greet
TOOLS = (
Tool(
func=greet,
inputs=GreetInput,
output=GreetOutput,
),
)
__all__ = ["TOOLS"]
- Instantiate the server:
# app/main.py
from starlette.applications import Starlette
from http_mcp.server import MCPServer
from app.tools import TOOLS
mcp_server = MCPServer(tools=TOOLS, name="test", version="1.0.0")
app = Starlette()
app.mount(
"/mcp",
mcp_server.app,
)
Tools Without Arguments
You can define tools that don't require any input arguments:
from datetime import UTC, datetime
from pydantic import BaseModel, Field
from http_mcp.types import Tool
class GetTimeOutput(BaseModel):
time: str = Field(description="The current time")
async def get_time() -> GetTimeOutput:
"""Get the current time."""
return GetTimeOutput(time=datetime.now(UTC).strftime("%H:%M:%S"))
TOOLS = (
Tool(
func=get_time,
inputs=type(None), # No arguments required
output=GetTimeOutput,
),
)
Alternatively, you can use the NoArguments class for better clarity:
from http_mcp.types import Arguments, NoArguments, Tool
class SimpleOutput(BaseModel):
success: bool = Field(description="Whether the operation was successful")
def simple_tool(args: Arguments[NoArguments]) -> SimpleOutput:
"""A simple tool with no arguments."""
# You can still access request and state
context = args.get_state_key("context", Context)
return SimpleOutput(success=True)
TOOLS = (
Tool(
func=simple_tool,
inputs=NoArguments,
output=SimpleOutput,
),
)
Tools with Error Handling
Tools can include structured feedback when an invocation fails:
from pydantic import BaseModel, Field
from http_mcp.types import Arguments, Tool
from http_mcp.exceptions import ToolInvocationError
class RiskyToolInput(BaseModel):
value: int = Field(description="An integer value")
class RiskyToolOutput(BaseModel):
result: str = Field(description="The result of the operation")
def risky_tool(args: Arguments[RiskyToolInput]) -> RiskyToolOutput:
"""A tool that might fail."""
if args.inputs.value < 0:
raise ToolInvocationError("risky_tool", "Value must be positive")
return RiskyToolOutput(result=f"Success: {args.inputs.value}")
TOOLS = (
Tool(
func=risky_tool,
inputs=RiskyToolInput,
output=RiskyToolOutput,
return_error_message=True, # Include structured ErrorMessage data on failure
),
)
Both error modes contain exceptions at the invocation boundary and return
isError:true. With return_error_message=True, the response additionally
preserves {"error_message": "..."} in structuredContent and as JSON text
content. Its output schema includes the ErrorMessage variant. Unexpected
exception details remain hidden.
Direct callers of Tool.invoke and custom ServerInterface implementations
must handle StructuredToolInvocationFailed from http_mcp.failures for this
mode. It carries the failure's message; the transport builds the structured
data. This replaces the previous plain ErrorMessage success outcome.
Tool Annotations
Supply hints explicitly with ToolAnnotations:
from http_mcp.types import Tool, ToolAnnotations
tool = Tool(
func=risky_tool,
inputs=RiskyToolInput,
output=RiskyToolOutput,
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
Available fields are title, read_only_hint, destructive_hint,
idempotent_hint, and open_world_hint. Unspecified safety hints are omitted;
the annotation title defaults to the tool's generated title. The server no
longer claims that every tool is non-destructive and idempotent.
Tool.annotations is now a typed, immutable ToolAnnotations model rather than
a mapping.
Tools with Authorization Scopes
You can restrict tool access based on authentication scopes:
from http_mcp.exceptions import ToolInvocationError
from http_mcp.types import Arguments, NoArguments, Tool
from starlette.authentication import has_required_scope
class SecureOutput(BaseModel):
message: str = Field(description="A secure message")
def private_tool(args: Arguments[NoArguments]) -> SecureOutput:
"""A tool that requires authentication."""
if not has_required_scope(args.request, ("private",)):
raise ToolInvocationError("private_tool", "Insufficient scope")
return SecureOutput(message="This is private data")
def admin_tool(args: Arguments[NoArguments]) -> SecureOutput:
"""A tool that requires admin or superuser scope."""
if not has_required_scope(args.request, ("admin", "superuser")):
raise ToolInvocationError("admin_tool", "Insufficient scope")
return SecureOutput(message="This is admin data")
TOOLS = (
Tool(
func=private_tool,
inputs=NoArguments,
output=SecureOutput,
scopes=("private",), # Only accessible with 'private' scope
),
Tool(
func=admin_tool,
inputs=NoArguments,
output=SecureOutput,
scopes=("admin", "superuser"), # Accessible with either scope
),
)
Note: You need to set up authentication middleware in your Starlette app for
scopes to work properly. The scopes field on Tool is the primary
authorization gate — the framework filters tools by scope before invocation. The
raise ToolInvocationError(...) calls inside the tool functions above are
optional defense-in-depth checks that return a proper error response to the
client instead of silently failing.
Server State Management
The server uses Starlette's lifespan system to manage shared state across the
entire application lifecycle. State is initialized when the application starts
and persists until it shuts down. Context is accessed through the
get_state_key method on the Arguments object.
This is useful for sharing resources like database connection pools, HTTP clients, caches, or any application state across tools.
Database Connection Pool
The most common pattern — initialize a connection pool at startup, share it across all tools, and close it on shutdown:
# app/context.py
from dataclasses import dataclass
import asyncpg
@dataclass
class AppContext:
db: asyncpg.Pool
# app/main.py
import contextlib
import os
from collections.abc import AsyncIterator
from typing import TypedDict
import asyncpg
from starlette.applications import Starlette
from http_mcp.server import MCPServer
from app.context import AppContext
class State(TypedDict):
ctx: AppContext
@contextlib.asynccontextmanager
async def lifespan(_app: Starlette) -> AsyncIterator[State]:
pool = await asyncpg.create_pool(os.environ["DATABASE_URL"])
yield {"ctx": AppContext(db=pool)}
await pool.close()
mcp_server = MCPServer(tools=TOOLS, name="my-server", version="1.0.0")
app = Starlette(lifespan=lifespan)
app.mount("/mcp", mcp_server.app)
# app/tools.py
from pydantic import BaseModel, Field
from http_mcp.types import Arguments
from app.context import AppContext
class GetUserInput(BaseModel):
user_id: int = Field(description="The user ID to look up")
class GetUserOutput(BaseModel):
name: str = Field(description="The user's name")
email: str = Field(description="The user's email")
async def get_user(args: Arguments[GetUserInput]) -> GetUserOutput:
"""Look up a user by ID."""
ctx = args.get_state_key("ctx", AppContext)
row = await ctx.db.fetchrow(
"SELECT name, email FROM users WHERE id = $1",
args.inputs.user_id,
)
return GetUserOutput(name=row["name"], email=row["email"])
Shared HTTP Client
Share a single httpx.AsyncClient across tools to reuse connections and
configure base URLs, headers, or timeouts once:
# app/context.py
from dataclasses import dataclass
import httpx
@dataclass
class AppContext:
http_client: httpx.AsyncClient
# app/main.py
import contextlib
from collections.abc import AsyncIterator
from typing import TypedDict
import httpx
from starlette.applications import Starlette
from http_mcp.server import MCPServer
from app.context import AppContext
class State(TypedDict):
ctx: AppContext
@contextlib.asynccontextmanager
async def lifespan(_app: Starlette) -> AsyncIterator[State]:
async with httpx.AsyncClient(
base_url="https://api.example.com",
headers={"Authorization": "Bearer <token>"},
) as client:
yield {"ctx": AppContext(http_client=client)}
mcp_server = MCPServer(tools=TOOLS, name="my-server", version="1.0.0")
app = Starlette(lifespan=lifespan)
app.mount("/mcp", mcp_server.app)
# app/tools.py
from pydantic import BaseModel, Field
from http_mcp.types import Arguments
from app.context import AppContext
class SearchInput(BaseModel):
query: str = Field(description="The search query")
class SearchOutput(BaseModel):
results: list[str] = Field(description="Search result titles")
async def search(args: Arguments[SearchInput]) -> SearchOutput:
"""Search via an external API."""
ctx = args.get_state_key("ctx", AppContext)
resp = await ctx.http_client.get("/search", params={"q": args.inputs.query})
resp.raise_for_status()
return SearchOutput(results=[r["title"] for r in resp.json()["items"]])
In-Memory Cache
Share mutable state like caches or counters across tool invocations within the same server lifecycle:
# app/context.py
from dataclasses import dataclass, field
@dataclass
class AppContext:
cache: dict[str, str] = field(default_factory=dict)
request_count: int = 0
# app/tools.py
from pydantic import BaseModel, Field
from http_mcp.types import Arguments
from app.context import AppContext
class LookupInput(BaseModel):
key: str = Field(description="The cache key to look up")
class LookupOutput(BaseModel):
value: str | None = Field(description="The cached value, or null if not found")
total_requests: int = Field(description="Total requests served")
async def lookup(args: Arguments[LookupInput]) -> LookupOutput:
"""Look up a value in the cache."""
ctx = args.get_state_key("ctx", AppContext)
ctx.request_count += 1
return LookupOutput(
value=ctx.cache.get(args.inputs.key),
total_requests=ctx.request_count,
)
All tools sharing the same AppContext instance see each other's writes
immediately, since the lifespan yields a single shared object.
Note: Plain dict and int are not thread-safe. If your tools run concurrently
(e.g., sync tools dispatched via threads), protect shared mutable state with an
asyncio.Lock or use thread-safe data structures.
Request Access
You can access the incoming request object from your tools. The request object is passed to each tool call and can be used to access headers, cookies, and other request data (e.g. request.state, request.scope).
from pydantic import BaseModel, Field
from http_mcp.types import Arguments
class MyToolArguments(BaseModel):
question: str = Field(description="The question to answer")
class MyToolOutput(BaseModel):
answer: str = Field(description="The answer to the question")
async def my_tool(args: Arguments[MyToolArguments]) -> MyToolOutput:
# Access the request
auth_header = args.request.headers.get("Authorization")
...
return MyToolOutput(answer=f"Hello, {args.inputs.question}!")
# Use MCPServer:
from http_mcp.server import MCPServer
mcp_server = MCPServer(
name="my-server",
version="1.0.0",
tools=(my_tool,),
)
Prompts
You can add interactive templates that are invoked by user choice. Prompts now support lifespan state access, similar to tools.
Basic Prompt Example
- Define the arguments for the prompts:
from pydantic import BaseModel, Field
from http_mcp.types import Arguments, Prompt, PromptMessage, TextContent
class GetAdvice(BaseModel):
topic: str = Field(description="The topic to get advice on")
include_actionable_steps: bool = Field(
description="Whether to include actionable steps in the advice", default=False
)
def get_advice(args: Arguments[GetAdvice]) -> tuple[PromptMessage, ...]:
"""Get advice on a topic."""
template = """
You are a helpful assistant that can give advice on {topic}.
"""
if args.inputs.include_actionable_steps:
template += """
The advice should include actionable steps.
"""
return (
PromptMessage(
role="user",
content=TextContent(
text=template.format(topic=args.inputs.topic)
),
),
)
PROMPTS = (
Prompt(
func=get_advice,
arguments_type=GetAdvice,
),
)
- Instantiate the server:
from starlette.applications import Starlette
from app.prompts import PROMPTS
from http_mcp.server import MCPServer
app = Starlette()
mcp_server = MCPServer(tools=(), prompts=PROMPTS, name="test", version="1.0.0")
app.mount(
"/mcp",
mcp_server.app,
)
Prompts Without Arguments
You can define prompts that don't require any input arguments:
from http_mcp.types import Prompt, PromptMessage, TextContent
def help_prompt() -> tuple[PromptMessage, ...]:
"""Use this prompt to get general help."""
return (
PromptMessage(
role="user",
content=TextContent(
text="You are a helpful assistant. Help the user with their task."
),
),
)
PROMPTS = (
Prompt(
func=help_prompt,
arguments_type=type(None), # No arguments required
),
)
Alternatively, you can use the NoArguments class:
from http_mcp.types import Arguments, NoArguments, Prompt, PromptMessage, TextContent
def help_prompt_with_context(args: Arguments[NoArguments]) -> tuple[PromptMessage, ...]:
"""Use this prompt to get help with access to context."""
# You can still access request and state
context = args.get_state_key("context", Context)
return (
PromptMessage(
role="user",
content=TextContent(text="You are a helpful assistant."),
),
)
PROMPTS = (
Prompt(
func=help_prompt_with_context,
arguments_type=NoArguments,
),
)
Prompts with Lifespan State
from pydantic import BaseModel, Field
from http_mcp.types import Arguments, Prompt, PromptMessage, TextContent
from app.context import Context
class GetAdvice(BaseModel):
topic: str = Field(description="The topic to get advice on")
def get_advice_with_context(args: Arguments[GetAdvice]) -> tuple[PromptMessage, ...]:
"""Get advice on a topic with context awareness."""
# Access the context from lifespan state
context = args.get_state_key("context", Context)
called_tools = context.get_called_tools()
template = """
You are a helpful assistant that can give advice on {topic}.
Previously called tools: {tools}
"""
return (
PromptMessage(
role="user",
content=TextContent(
text=template.format(
topic=args.inputs.topic,
tools=", ".join(called_tools) if called_tools else "none"
)
)
),
)
PROMPTS_WITH_CONTEXT = (
Prompt(
func=get_advice_with_context,
arguments_type=GetAdvice,
),
)
Prompts with Authorization Scopes
You can restrict prompt access based on authentication scopes:
from http_mcp.types import Arguments, NoArguments, Prompt, PromptMessage, TextContent
def private_prompt(args: Arguments[NoArguments]) -> tuple[PromptMessage, ...]:
"""Private prompt that is only accessible to authenticated users."""
return (
PromptMessage(
role="user",
content=TextContent(text="This is a private prompt."),
),
)
def admin_prompt(args: Arguments[NoArguments]) -> tuple[PromptMessage, ...]:
"""Admin prompt accessible to users with admin or superuser scope."""
return (
PromptMessage(
role="user",
content=TextContent(text="This is an admin prompt."),
),
)
PROMPTS = (
Prompt(
func=private_prompt,
arguments_type=NoArguments,
scopes=("private",), # Only accessible with 'private' scope
),
Prompt(
func=admin_prompt,
arguments_type=NoArguments,
scopes=("admin", "superuser"), # Accessible with either scope
),
)
Note: You need to set up authentication middleware in your Starlette app for scopes to work properly.
STDIO Transport
In addition to HTTP transport, the server supports STDIO transport for communication. This is useful for command-line applications and integrations that communicate through standard input/output.
Using STDIO Transport
import asyncio
import os
from http_mcp.server import MCPServer
from app.tools import TOOLS
from app.prompts import PROMPTS
mcp_server = MCPServer(
tools=TOOLS,
prompts=PROMPTS,
name="test",
version="1.0.0"
)
# Run the server with STDIO transport
async def main() -> None:
request_headers = {
"Authorization": f"Bearer {os.getenv('MCP_TOKEN', '')}",
"X-Custom-Header": "value",
}
await mcp_server.serve_stdio(request_headers)
asyncio.run(main())
The request_headers parameter allows you to pass headers that will be included
in the request context, enabling authentication and other header-based features
even when using STDIO transport.
While serve_stdio runs, the process's stdout is reserved for protocol frames:
file descriptor 1 is pointed at stderr, so print() in a tool, a chatty
library, or a child process cannot write something the client would read as a
message. Scope-restricted tools and prompts are always denied over STDIO,
because there is no authentication middleware, and the error does not name the
scopes.
Authentication and Authorization
The library integrates with Starlette's authentication system to provide scope-based authorization for tools and prompts.
Setting Up Authentication Middleware
import contextlib
from collections.abc import AsyncIterator
from typing import TypedDict
from starlette.applications import Starlette
from starlette.authentication import (
AuthCredentials,
AuthenticationBackend,
BaseUser,
SimpleUser,
)
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import HTTPConnection
from http_mcp.server import MCPServer
from app.context import Context
from app.tools import TOOLS
from app.prompts import PROMPTS
class BasicAuthBackend(AuthenticationBackend):
def __init__(self, granted_scopes: tuple[str, ...] = ("authenticated",)) -> None:
self.granted_scopes = granted_scopes
super().__init__()
async def authenticate(
self, conn: HTTPConnection
) -> tuple[AuthCredentials, BaseUser] | None:
# Implement your authentication logic here
# For example, check Bearer token, API key, etc.
auth_header = conn.headers.get("Authorization")
if not auth_header:
return None
# Validate token and return credentials with scopes
return AuthCredentials(self.granted_scopes), SimpleUser("username")
class State(TypedDict):
context: Context
@contextlib.asynccontextmanager
async def lifespan(_app: Starlette) -> AsyncIterator[State]:
yield {"context": Context()}
mcp_server = MCPServer(
tools=TOOLS,
prompts=PROMPTS,
name="test",
version="1.0.0"
)
app = Starlette(
lifespan=lifespan,
middleware=[
Middleware(
AuthenticationMiddleware,
backend=BasicAuthBackend(granted_scopes=("private", "admin")),
),
],
)
app.mount("/mcp", mcp_server.app)
How Scopes Work
-
Authentication Middleware: The middleware authenticates each request and assigns scopes to the user through
AuthCredentials. -
Tool/Prompt Scopes: When defining tools or prompts, you can specify required scopes using the
scopesparameter. -
Access Control: The server automatically filters tools and prompts based on the user's granted scopes. Tools and prompts without the required scopes are not visible in listings and cannot be invoked.
-
Multiple Scopes: If you specify multiple scopes (e.g.,
scopes=("admin", "superuser")), the user needs at least one of those scopes to access the tool or prompt. -
Step-up: Calling a tool or prompt without its scopes gets
403 ForbiddenwithWWW-Authenticate: Bearer error="insufficient_scope", scope="admin superuser", which is what lets an OAuth client request a token with more scopes. The trade-off is deliberate: a caller can tell a hidden tool (403) from an unknown one (-32602) and learn which scopes it needs, though never its description or schema. Do not encode secrets in tool, prompt, or scope names.
API Reference
Tool Class
The Tool class is used to define tools that can be invoked by clients.
Parameters:
func: The function to be invoked. Can be sync or async. The function can either:- Accept an
Arguments[TInputs]parameter - Accept no parameters
- Accept an
inputs: The Pydantic model class for input validation. Usetype(None)orNoArgumentsfor tools without inputsoutput: The Pydantic model class defining the output schema and serializationreturn_error_message(bool): IfTrue, failed invocations include structuredErrorMessagedata while retainingisError:true(default:False)scopes(tuple[str, ...]): Required authentication scopes for accessing this tool (default: empty tuple)annotations(ToolAnnotations): Explicit hints; unspecified safety hints are omitted
Properties:
name: The function name (derived fromfunc.__name__)title: A human-readable title (derived from the function name)description: The function's docstringinput_schema: JSON schema for the input parametersoutput_schema: JSON schema for the output
Prompt Class
The Prompt class is used to define prompts that can be invoked by clients.
Import the return-content types through the public API:
from http_mcp.types import Prompt, PromptMessage, TextContent
Prompt functions return tuple[PromptMessage, ...], with text messages
containing TextContent. These are public exports; application code does not
need to import http_mcp._mcp_types.
Parameters:
func: The function to be invoked. Can be sync or async. The function can either:- Accept an
Arguments[TArguments]parameter - Accept no parameters
- Must return
tuple[PromptMessage, ...]
- Accept an
arguments_type: The Pydantic model class for argument validation. Usetype(None)orNoArgumentsfor prompts without argumentsscopes(tuple[str, ...]): Required authentication scopes for accessing this prompt (default: empty tuple)
Properties:
name: The function name (derived fromfunc.__name__)title: A human-readable title (derived from the function name)description: The function's docstringarguments: Tuple ofPromptArgumentobjects defining the prompt's arguments
Arguments Class
The Arguments class is passed to tool and prompt functions to provide access
to inputs, request, and state.
Parameters:
request: The StarletteRequestobjectinputs: The validated input/argument data (type depends on the Tool/Prompt definition)
Methods:
get_state_key(key: str, _object_type: type[TKey]) -> TKey: Access a value from the lifespan state. RaisesServerErrorif the key doesn't exist.
NoArguments Class
An empty Pydantic model that can be used as a clearer alternative to
type(None) when defining tools or prompts without arguments.
from http_mcp.types import NoArguments
# Use this instead of type(None)
Tool(func=my_func, inputs=NoArguments, output=MyOutput)
OAuth 2.1 Authorization (auth_mcp)
The auth_mcp package adds standards-compliant OAuth 2.1 authorization to your
MCP server. Install with the auth extra:
pip install http-mcp[auth]
Quick Start
from http_mcp.server import MCPServer
from auth_mcp.resource_server import (
ProtectedMCPAppConfig,
TokenInfo,
TokenValidator,
create_protected_mcp_app,
)
from auth_mcp.types import ProtectedResourceMetadata
class MyTokenValidator(TokenValidator):
async def validate_token(
self, token: str, resource: str | None = None
) -> TokenInfo | None:
# Validate against your authorization server
...
mcp_server = MCPServer(name="my-server", version="1.0.0", tools=MY_TOOLS)
config = ProtectedMCPAppConfig(
mcp_server=mcp_server,
token_validator=MyTokenValidator(),
resource_endpoint=ProtectedResourceMetadata(
resource="https://mcp.example.com",
authorization_servers=("https://auth.example.com",),
),
)
app = create_protected_mcp_app(config)
This gives you:
- Bearer token validation on all MCP endpoints (secure by default)
/.well-known/oauth-protected-resourcediscovery endpoint (RFC 9728)WWW-Authenticateheaders on 401/403 withresource_metadataparameter- Security headers (HSTS, nosniff, no-store)
- MCP-only custom middleware via
ProtectedMCPAppConfig.middlewares - App-wide middleware via
create_protected_mcp_app(config, middleware=[...])
Applying Middleware to Selected Paths
The built-in token_validator runs only on the MCP mount (/mcp by default).
Protected-resource discovery, authorization-server metadata and /register
remain outside that authentication stack. config.middlewares also applies only
to the configured MCP mount; put additional token-validation middleware there to
exclude the public OAuth endpoints.
Starlette's Middleware(...) declaration does not add path filtering by itself;
the helper uses a Mount to establish that boundary. Adding authentication to
the app-wide list would also authenticate OAuth endpoints unless that middleware
implements its own exclusions.
App-wide middleware is explicit. For example, apply CORS to all endpoints while
keeping token validation on /mcp:
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
# config.token_validator still validates only requests under config.mcp_path.
app = create_protected_mcp_app(
config,
middleware=[
Middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_methods=["GET", "POST"],
allow_headers=[
"Authorization", "Content-Type", "MCP-Protocol-Version",
"Mcp-Method", "Mcp-Name",
],
expose_headers=["WWW-Authenticate"],
),
],
)
The MCP server must also list the browser's origin in allowed_origins. Any
middleware supplied through the app-wide middleware keyword runs for OAuth
endpoints too. If you used the earlier prerelease's app-wide
config.middlewares behavior, move those entries to this keyword. Starlette's
mount-level middleware provides the path selection without a custom URL filter.
For a local plain-HTTP authorization server, see the explicit development opt-in.
For full documentation, best practices, and security surface details, see auth_mcp README.
Security Surfaces by Endpoint
POST /mcp — MCP JSON-RPC Endpoint
- Authentication — When using
auth_mcp, Bearer tokens are extracted from theAuthorizationheader and validated viaTokenValidator. Tokens exceeding 2048 characters or containing characters outside the RFC 6750b64tokenpattern are rejected before reaching the validator. Withoutauth_mcp, authentication is handled by Starlette'sAuthenticationMiddleware. - Authorization — Scope-based filtering via Starlette's
has_required_scope(). Tools and prompts without matching scopes are hidden from listings and blocked on invocation. Request-header validation resolves tool schemas through the same scope check, so a caller a tool is hidden from cannot learn itsx-mcp-headerarguments from a mismatch message either. - Input validation — JSON-RPC messages validated by Pydantic. Request body
capped at 4 MB, enforced while reading: an oversized
Content-Lengthis refused before the body is read at all, and a body that outgrows the cap mid-stream stops being buffered at that point. Content-Type strictly checked (application/jsononly, media type parameters ignored). - Header mirroring — Each mirrored header is compared with the body and must appear once; aliases on header-mirrored arguments are refused at construction.
- Origin — Only loopback origins are accepted unless
allowed_originsis set (DNS-rebinding defence). - Error handling — Tool and prompt names truncated to 100 characters in
error messages. Pydantic validation errors sanitized before inclusion in
responses. Wiring errors from
Arguments.get_state_keyreach the client asInternal server error, with the detail logged. - Response headers —
X-Content-Type-Options: nosniff,Cache-Control: no-storeon all responses.auth_mcpadditionally addsStrict-Transport-Security: max-age=31536000; includeSubDomains.
GET /.well-known/oauth-protected-resource — Discovery Endpoint (auth_mcp)
- Authentication — None. The route sits outside the auth middleware that
wraps
/mcp, because RFC 9728 discovery is how an unauthenticated client finds the authorization server; it serves public metadata only. - Input validation — Only
GETallowed; other methods return405 Method Not Allowed. - Output — Serialized once at startup from a frozen
ProtectedResourceMetadatamodel. Resource/documentation URLs use Pydantic'sAnyHttpUrl; authorization-server issuers are validated strings whose exact spelling is preserved.
WWW-Authenticate Response Header (auth_mcp)
- Header injection — All parameter values (
realm,resource_metadata,scope,error,error_description) are sanitized: every character outside visible ASCII and space is stripped (CR, LF, NUL, other controls, NEL, U+2028), then backslash and double-quote are escaped per RFC 9110 quoted-string rules. The scheme must be an RFC 9110 token. - Information disclosure — Error responses use generic messages
(
"Authentication required"). The originalAuthenticationErrordetails are discarded. Error codes follow RFC 6750:invalid_tokenon a 401 only when a Bearer token was presented, none when the request carried no credentials, andinsufficient_scopewith the requiredscopeon a 403.
STDIO Transport
- Message size — Capped at 4 MB, matching HTTP transport. An oversized line is answered with an error and skipped to its newline; the session continues.
- Output — Protocol frames are the only thing written to stdout; the
process's stdout is redirected to stderr while
serve_stdioruns. - Logging — Messages truncated to 500 characters in debug logs to prevent log flooding. Token values are never logged.
- Headers — Request headers are converted to proper ASGI
list[tuple[bytes, bytes]]format.
Installation
Requires Python 3.12+ (uses PEP 695 type parameter syntax).
Install the package using pip or uv:
pip install http-mcp
With OAuth 2.1 authorization support:
pip install http-mcp[auth]
or
uv add http-mcp
License
This project is licensed under the MIT License. See the LICENSE file for details.
Metadata
Release files for http-mcp 0.19.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| http_mcp-0.19.0.tar.gz | 639.1 kB | Without provenance | Details for http_mcp-0.19.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| http_mcp-0.19.0-py3-none-any.whl | Python 3 | none | any | Details for http_mcp-0.19.0-py3-none-any.whl |
Total release size: 723.2 kB
Release files / http_mcp-0.19.0.tar.gz
| Download URL | http_mcp-0.19.0.tar.gz |
|---|---|
| Size | 639.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a0f0491686593012f6f2a4d8fd68db642f4aad623302c78b39983df1f18cb1a4
|
|
BLAKE2b-256 checksum How to use checksums |
4e95b17a5b4d11e4017974a385d6957241895c76dd1c9499f43fcfedb0bf1323
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / http_mcp-0.19.0-py3-none-any.whl
| Download URL | http_mcp-0.19.0-py3-none-any.whl |
|---|---|
| Size | 84.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bc541a688b7dcc91c235c8d90030c24f2981eb691e0901523191eaee0a9d3787
|
|
BLAKE2b-256 checksum How to use checksums |
196be73a875b9e3dc5f2eb1c727c5098d479f561cb4340698830bca872502d31
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for http-mcp 0.19.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.