MCP: mcp 2.3 (MCPServer, transport arguments on streamable_http_app, bearer read in middleware); tests for the 2026-07-28 revision and the resource check
Claude-Session: https://claude.ai/code/session_01SSi5AvZ7pFmySK8zy3NPMh
This commit is contained in:
@@ -20,7 +20,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from mcp.types import TextContent
|
||||
from mcp.types import CallToolResult, TextContent
|
||||
|
||||
from fluksio.ai import client
|
||||
from fluksio.ai.config import AIConfig
|
||||
@@ -68,7 +68,7 @@ async def tool_specs() -> list[dict[str, Any]]:
|
||||
"function": {
|
||||
"name": tool.name,
|
||||
"description": tool.description or "",
|
||||
"parameters": tool.inputSchema,
|
||||
"parameters": tool.input_schema,
|
||||
},
|
||||
}
|
||||
for tool in await mcp.list_tools()
|
||||
@@ -108,10 +108,9 @@ async def _call_tool(name: str, arguments: dict[str, Any]) -> str:
|
||||
result = await mcp.call_tool(name, arguments)
|
||||
except Exception as exc: # noqa: BLE001 - an unknown tool, or refused arguments
|
||||
return json.dumps({"error": str(exc)})
|
||||
if isinstance(result, dict):
|
||||
text = json.dumps(result)
|
||||
else:
|
||||
text = "".join(c.text for c in result if isinstance(c, TextContent))
|
||||
if not isinstance(result, CallToolResult):
|
||||
return json.dumps({"error": "The tool asked for more input than a chat gives."})
|
||||
text = "".join(c.text for c in result.content if isinstance(c, TextContent))
|
||||
if len(text) > _RESULT_LIMIT:
|
||||
text = text[:_RESULT_LIMIT] + "… (truncated)"
|
||||
return text
|
||||
|
||||
@@ -167,18 +167,21 @@ class _ThroughThePortal:
|
||||
|
||||
def build_http_app(app: object) -> ASGIApp:
|
||||
"""The MCP sub-app, wired to this app's API and its OAuth server."""
|
||||
server.mcp.settings.stateless_http = True
|
||||
server.mcp.settings.json_response = True
|
||||
server.mcp.settings.auth = AuthSettings(
|
||||
issuer_url=AnyHttpUrl(settings.oauth_issuer),
|
||||
resource_server_url=AnyHttpUrl(settings.mcp_resource),
|
||||
required_scopes=None,
|
||||
validate_token_resource=True,
|
||||
)
|
||||
server.mcp.settings.transport_security = _transport_security()
|
||||
# The SDK only takes a verifier through its constructor, and the instance is
|
||||
# module-level so the tools can be declared at import time.
|
||||
server.mcp._token_verifier = _JWTVerifier() # noqa: SLF001
|
||||
|
||||
server.connect(app)
|
||||
return _ThroughThePortal(server.mcp.streamable_http_app())
|
||||
return _ThroughThePortal(
|
||||
server.mcp.streamable_http_app(
|
||||
stateless_http=True,
|
||||
json_response=True,
|
||||
transport_security=_transport_security(),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -13,24 +13,46 @@ identity rather than some service account.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import warnings
|
||||
from contextvars import ContextVar
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
from mcp.server.lowlevel.server import request_ctx
|
||||
from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
|
||||
from mcp.server.mcpserver import MCPServer
|
||||
|
||||
from fluksio.sdk.client import seg as _seg
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# FastMCP's own settings model leaves `lifespan` a forward reference, which
|
||||
# pydantic-settings warns about on every start. Nothing reads that field from
|
||||
# the environment, so the warning says nothing about this app.
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", message="Field 'lifespan' has an incomplete")
|
||||
mcp = FastMCP("fluksio")
|
||||
#: The ``Authorization`` value tool calls carry onto the REST API. The endpoint's
|
||||
#: middleware sets it from each MCP request; the assistant sets it to the token of
|
||||
#: the person chatting, for the length of their turn, since no MCP request is
|
||||
#: involved there.
|
||||
caller_authorization: ContextVar[str | None] = ContextVar(
|
||||
"caller_authorization", default=None
|
||||
)
|
||||
|
||||
|
||||
async def _carry_authorization(
|
||||
ctx: ServerRequestContext[Any, Any], call_next: CallNext
|
||||
) -> HandlerResult:
|
||||
"""Make the bearer token of an MCP request the caller's for its tool calls.
|
||||
|
||||
The transport attaches the originating HTTP request to every JSON-RPC
|
||||
message, so the token is read per message rather than per connection.
|
||||
"""
|
||||
headers = getattr(ctx.request, "headers", None)
|
||||
authorization = headers.get("authorization") if headers else None
|
||||
if not authorization:
|
||||
return await call_next(ctx)
|
||||
token = caller_authorization.set(authorization)
|
||||
try:
|
||||
return await call_next(ctx)
|
||||
finally:
|
||||
caller_authorization.reset(token)
|
||||
|
||||
|
||||
mcp = MCPServer("fluksio", middleware=[_carry_authorization])
|
||||
|
||||
#: The tool calls never leave the process, so the host is a label, not a route.
|
||||
_INTERNAL_BASE = "http://fluksio-mcp.internal"
|
||||
@@ -39,13 +61,6 @@ _INTERNAL_BASE = "http://fluksio-mcp.internal"
|
||||
#: hop. Built once by :func:`connect`, for the endpoint and the assistant alike.
|
||||
_client: httpx.AsyncClient | None = None
|
||||
|
||||
#: The ``Authorization`` value for tool calls made from inside this process,
|
||||
#: where no MCP request carries one: the assistant sets it to the token of the
|
||||
#: person chatting, for the length of their turn.
|
||||
caller_authorization: ContextVar[str | None] = ContextVar(
|
||||
"caller_authorization", default=None
|
||||
)
|
||||
|
||||
|
||||
def set_client(client: httpx.AsyncClient | None) -> None:
|
||||
global _client
|
||||
@@ -77,18 +92,10 @@ async def aclose() -> None:
|
||||
async def forward_caller_auth(request: httpx.Request) -> None:
|
||||
"""Carry the caller's bearer token onto the REST call.
|
||||
|
||||
Over the endpoint, the transport attaches the originating HTTP request to
|
||||
every JSON-RPC message, and a tool handler runs inside that request's
|
||||
context, so the token is read per message rather than per connection. A
|
||||
call from inside the process has no such request and uses what
|
||||
:data:`caller_authorization` holds.
|
||||
A tool handler runs inside the context :data:`caller_authorization` was set
|
||||
in, by the endpoint's middleware or by the assistant.
|
||||
"""
|
||||
authorization = caller_authorization.get()
|
||||
try:
|
||||
source = request_ctx.get().request
|
||||
except LookupError:
|
||||
source = None
|
||||
authorization = getattr(source, "headers", {}).get("authorization") or authorization
|
||||
if authorization:
|
||||
request.headers["authorization"] = authorization
|
||||
|
||||
|
||||
Reference in New Issue
Block a user