chore: import upstream snapshot with attribution
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Low-level server examples for MCP Python SDK."""
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Run from the repository root:
|
||||
uv run examples/snippets/servers/lowlevel/basic.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import mcp_types as types
|
||||
|
||||
import mcp.server.stdio
|
||||
from mcp.server import Server, ServerRequestContext
|
||||
|
||||
|
||||
async def handle_list_prompts(
|
||||
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
|
||||
) -> types.ListPromptsResult:
|
||||
"""List available prompts."""
|
||||
return types.ListPromptsResult(
|
||||
prompts=[
|
||||
types.Prompt(
|
||||
name="example-prompt",
|
||||
description="An example prompt template",
|
||||
arguments=[types.PromptArgument(name="arg1", description="Example argument", required=True)],
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def handle_get_prompt(ctx: ServerRequestContext, params: types.GetPromptRequestParams) -> types.GetPromptResult:
|
||||
"""Get a specific prompt by name."""
|
||||
if params.name != "example-prompt":
|
||||
raise ValueError(f"Unknown prompt: {params.name}")
|
||||
|
||||
arg1_value = (params.arguments or {}).get("arg1", "default")
|
||||
|
||||
return types.GetPromptResult(
|
||||
description="Example prompt",
|
||||
messages=[
|
||||
types.PromptMessage(
|
||||
role="user",
|
||||
content=types.TextContent(type="text", text=f"Example prompt text with argument: {arg1_value}"),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
server = Server(
|
||||
"example-server",
|
||||
on_list_prompts=handle_list_prompts,
|
||||
on_get_prompt=handle_get_prompt,
|
||||
)
|
||||
|
||||
|
||||
async def run():
|
||||
"""Run the basic low-level server."""
|
||||
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
||||
await server.run(
|
||||
read_stream,
|
||||
write_stream,
|
||||
server.create_initialization_options(),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Run from the repository root:
|
||||
uv run examples/snippets/servers/lowlevel/direct_call_tool_result.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import mcp_types as types
|
||||
|
||||
import mcp.server.stdio
|
||||
from mcp.server import Server, ServerRequestContext
|
||||
|
||||
|
||||
async def handle_list_tools(
|
||||
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
|
||||
) -> types.ListToolsResult:
|
||||
"""List available tools."""
|
||||
return types.ListToolsResult(
|
||||
tools=[
|
||||
types.Tool(
|
||||
name="advanced_tool",
|
||||
description="Tool with full control including _meta field",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {"message": {"type": "string"}},
|
||||
"required": ["message"],
|
||||
},
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def handle_call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> types.CallToolResult:
|
||||
"""Handle tool calls by returning CallToolResult directly."""
|
||||
if params.name == "advanced_tool":
|
||||
message = (params.arguments or {}).get("message", "")
|
||||
return types.CallToolResult(
|
||||
content=[types.TextContent(type="text", text=f"Processed: {message}")],
|
||||
structured_content={"result": "success", "message": message},
|
||||
_meta={"hidden": "data for client applications only"},
|
||||
)
|
||||
|
||||
raise ValueError(f"Unknown tool: {params.name}")
|
||||
|
||||
|
||||
server = Server(
|
||||
"example-server",
|
||||
on_list_tools=handle_list_tools,
|
||||
on_call_tool=handle_call_tool,
|
||||
)
|
||||
|
||||
|
||||
async def run():
|
||||
"""Run the server."""
|
||||
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
||||
await server.run(
|
||||
read_stream,
|
||||
write_stream,
|
||||
server.create_initialization_options(),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Run from the repository root:
|
||||
uv run examples/snippets/servers/lowlevel/lifespan.py
|
||||
"""
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import TypedDict
|
||||
|
||||
import mcp_types as types
|
||||
|
||||
import mcp.server.stdio
|
||||
from mcp.server import Server, ServerRequestContext
|
||||
|
||||
|
||||
# Mock database class for example
|
||||
class Database:
|
||||
"""Mock database class for example."""
|
||||
|
||||
@classmethod
|
||||
async def connect(cls) -> "Database":
|
||||
"""Connect to database."""
|
||||
print("Database connected")
|
||||
return cls()
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
"""Disconnect from database."""
|
||||
print("Database disconnected")
|
||||
|
||||
async def query(self, query_str: str) -> list[dict[str, str]]:
|
||||
"""Execute a query."""
|
||||
# Simulate database query
|
||||
return [{"id": "1", "name": "Example", "query": query_str}]
|
||||
|
||||
|
||||
class AppContext(TypedDict):
|
||||
db: Database
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def server_lifespan(_server: Server[AppContext]) -> AsyncIterator[AppContext]:
|
||||
"""Manage server startup and shutdown lifecycle."""
|
||||
db = await Database.connect()
|
||||
try:
|
||||
yield {"db": db}
|
||||
finally:
|
||||
await db.disconnect()
|
||||
|
||||
|
||||
async def handle_list_tools(
|
||||
ctx: ServerRequestContext[AppContext], params: types.PaginatedRequestParams | None
|
||||
) -> types.ListToolsResult:
|
||||
"""List available tools."""
|
||||
return types.ListToolsResult(
|
||||
tools=[
|
||||
types.Tool(
|
||||
name="query_db",
|
||||
description="Query the database",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {"query": {"type": "string", "description": "SQL query to execute"}},
|
||||
"required": ["query"],
|
||||
},
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def handle_call_tool(
|
||||
ctx: ServerRequestContext[AppContext], params: types.CallToolRequestParams
|
||||
) -> types.CallToolResult:
|
||||
"""Handle database query tool call."""
|
||||
if params.name != "query_db":
|
||||
raise ValueError(f"Unknown tool: {params.name}")
|
||||
|
||||
db = ctx.lifespan_context["db"]
|
||||
results = await db.query((params.arguments or {})["query"])
|
||||
|
||||
return types.CallToolResult(content=[types.TextContent(type="text", text=f"Query results: {results}")])
|
||||
|
||||
|
||||
server = Server(
|
||||
"example-server",
|
||||
lifespan=server_lifespan,
|
||||
on_list_tools=handle_list_tools,
|
||||
on_call_tool=handle_call_tool,
|
||||
)
|
||||
|
||||
|
||||
async def run():
|
||||
"""Run the server with lifespan management."""
|
||||
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
||||
await server.run(
|
||||
read_stream,
|
||||
write_stream,
|
||||
server.create_initialization_options(),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import asyncio
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Run from the repository root:
|
||||
uv run examples/snippets/servers/lowlevel/structured_output.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import mcp_types as types
|
||||
|
||||
import mcp.server.stdio
|
||||
from mcp.server import Server, ServerRequestContext
|
||||
|
||||
|
||||
async def handle_list_tools(
|
||||
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
|
||||
) -> types.ListToolsResult:
|
||||
"""List available tools with structured output schemas."""
|
||||
return types.ListToolsResult(
|
||||
tools=[
|
||||
types.Tool(
|
||||
name="get_weather",
|
||||
description="Get current weather for a city",
|
||||
input_schema={
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string", "description": "City name"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
output_schema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"temperature": {"type": "number", "description": "Temperature in Celsius"},
|
||||
"condition": {"type": "string", "description": "Weather condition"},
|
||||
"humidity": {"type": "number", "description": "Humidity percentage"},
|
||||
"city": {"type": "string", "description": "City name"},
|
||||
},
|
||||
"required": ["temperature", "condition", "humidity", "city"],
|
||||
},
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def handle_call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> types.CallToolResult:
|
||||
"""Handle tool calls with structured output."""
|
||||
if params.name == "get_weather":
|
||||
city = (params.arguments or {})["city"]
|
||||
|
||||
weather_data = {
|
||||
"temperature": 22.5,
|
||||
"condition": "partly cloudy",
|
||||
"humidity": 65,
|
||||
"city": city,
|
||||
}
|
||||
|
||||
return types.CallToolResult(
|
||||
content=[types.TextContent(type="text", text=json.dumps(weather_data, indent=2))],
|
||||
structured_content=weather_data,
|
||||
)
|
||||
|
||||
raise ValueError(f"Unknown tool: {params.name}")
|
||||
|
||||
|
||||
server = Server(
|
||||
"example-server",
|
||||
on_list_tools=handle_list_tools,
|
||||
on_call_tool=handle_call_tool,
|
||||
)
|
||||
|
||||
|
||||
async def run():
|
||||
"""Run the structured output server."""
|
||||
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
||||
await server.run(
|
||||
read_stream,
|
||||
write_stream,
|
||||
server.create_initialization_options(),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
Reference in New Issue
Block a user