Serve subscriptions/listen with a pluggable event bus (SEP-2575) (#3035)
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
from mcp.server.mcpserver import Context, MCPServer
|
||||
|
||||
mcp = MCPServer("Notebook")
|
||||
|
||||
NOTES = {"todo": "buy milk", "journal": "day one"}
|
||||
|
||||
|
||||
@mcp.resource("note://{name}")
|
||||
def note(name: str) -> str:
|
||||
return NOTES[name]
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def edit_note(name: str, text: str, ctx: Context) -> str:
|
||||
NOTES[name] = text
|
||||
await ctx.notify_resource_updated(f"note://{name}")
|
||||
return "saved"
|
||||
|
||||
|
||||
def search(query: str) -> list[str]:
|
||||
return [name for name, text in NOTES.items() if query in text]
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def enable_search(ctx: Context) -> str:
|
||||
mcp.add_tool(search)
|
||||
await ctx.notify_tools_changed()
|
||||
return "search is live"
|
||||
@@ -0,0 +1,40 @@
|
||||
from typing import Any
|
||||
|
||||
import mcp_types as types
|
||||
|
||||
from mcp.server.context import ServerRequestContext
|
||||
from mcp.server.lowlevel import Server
|
||||
from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, ResourceUpdated
|
||||
|
||||
bus = InMemorySubscriptionBus()
|
||||
|
||||
NOTES = {"todo": "buy milk"}
|
||||
|
||||
EDIT_NOTE_SCHEMA: dict[str, Any] = {
|
||||
"type": "object",
|
||||
"properties": {"name": {"type": "string"}, "text": {"type": "string"}},
|
||||
"required": ["name", "text"],
|
||||
}
|
||||
|
||||
|
||||
async def list_tools(
|
||||
ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
|
||||
) -> types.ListToolsResult:
|
||||
return types.ListToolsResult(
|
||||
tools=[types.Tool(name="edit_note", description="Replace a note's text.", input_schema=EDIT_NOTE_SCHEMA)]
|
||||
)
|
||||
|
||||
|
||||
async def call_tool(ctx: ServerRequestContext[Any], params: types.CallToolRequestParams) -> types.CallToolResult:
|
||||
args = params.arguments or {}
|
||||
NOTES[args["name"]] = args["text"]
|
||||
await bus.publish(ResourceUpdated(uri=f"note://{args['name']}"))
|
||||
return types.CallToolResult(content=[types.TextContent(type="text", text="saved")])
|
||||
|
||||
|
||||
server = Server(
|
||||
"notebook",
|
||||
on_list_tools=list_tools,
|
||||
on_call_tool=call_tool,
|
||||
on_subscriptions_listen=ListenHandler(bus),
|
||||
)
|
||||
Reference in New Issue
Block a user