Add story-style examples suite (27 stories + harness + CI) (#2957)
This commit is contained in:
parent
9dc8c5f02d
commit
4caa41f6d5
1 changed files with 6801 additions and 26 deletions
54
examples/stories/middleware/server.py
Normal file
54
examples/stories/middleware/server.py
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
"""Dispatch-layer middleware: `Server.middleware` is the public hook.
|
||||
|
||||
A lowlevel-only story: `MCPServer` has no public middleware accessor yet, so the
|
||||
one supported registration point is the `middleware` list on `lowlevel.Server`.
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import mcp_types as types
|
||||
|
||||
from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
|
||||
from mcp.server.lowlevel import Server
|
||||
from stories._hosting import run_server_from_args
|
||||
|
||||
|
||||
def build_server() -> Server[Any]:
|
||||
log: list[str] = []
|
||||
|
||||
async def record_calls(ctx: ServerRequestContext[Any], call_next: CallNext) -> HandlerResult:
|
||||
log.append(ctx.method)
|
||||
try:
|
||||
return await call_next(ctx)
|
||||
finally:
|
||||
log.append(f"{ctx.method}:done")
|
||||
|
||||
async def list_tools(
|
||||
ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
|
||||
) -> types.ListToolsResult:
|
||||
return types.ListToolsResult(
|
||||
tools=[
|
||||
types.Tool(
|
||||
name="audit_log",
|
||||
description="Return every method the middleware has observed so far.",
|
||||
input_schema={"type": "object"},
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
async def call_tool(ctx: ServerRequestContext[Any], params: types.CallToolRequestParams) -> types.CallToolResult:
|
||||
assert params.name == "audit_log"
|
||||
snapshot = list(log)
|
||||
return types.CallToolResult(
|
||||
content=[types.TextContent(text=json.dumps(snapshot))],
|
||||
structured_content={"result": snapshot},
|
||||
)
|
||||
|
||||
server = Server("middleware-example", on_list_tools=list_tools, on_call_tool=call_tool)
|
||||
server.middleware.append(record_calls)
|
||||
return server
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_server_from_args(build_server)
|
||||
Loading…
Reference in a new issue