README - replace code snippets with examples (#1136)
This commit is contained in:
parent
49991fd2c7
commit
9bf5160eea
3 changed files with 585 additions and 169 deletions
0
examples/snippets/clients/__init__.py
Normal file
0
examples/snippets/clients/__init__.py
Normal file
80
examples/snippets/clients/completion_client.py
Normal file
80
examples/snippets/clients/completion_client.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
"""MCP client example showing completion usage.
|
||||
|
||||
This example demonstrates how to use the completion feature in MCP clients.
|
||||
cd to the `examples/snippets` directory and run:
|
||||
uv run completion-client
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from mcp import ClientSession, StdioServerParameters
|
||||
from mcp.client.stdio import stdio_client
|
||||
from mcp.types import PromptReference, ResourceTemplateReference
|
||||
|
||||
# Create server parameters for stdio connection
|
||||
server_params = StdioServerParameters(
|
||||
command="uv", # Using uv to run the server
|
||||
args=["run", "server", "completion", "stdio"], # Server with completion support
|
||||
env={"UV_INDEX": os.environ.get("UV_INDEX", "")},
|
||||
)
|
||||
|
||||
|
||||
async def run():
|
||||
"""Run the completion client example."""
|
||||
async with stdio_client(server_params) as (read, write):
|
||||
async with ClientSession(read, write) as session:
|
||||
# Initialize the connection
|
||||
await session.initialize()
|
||||
|
||||
# List available resource templates
|
||||
templates = await session.list_resource_templates()
|
||||
print("Available resource templates:")
|
||||
for template in templates.resourceTemplates:
|
||||
print(f" - {template.uriTemplate}")
|
||||
|
||||
# List available prompts
|
||||
prompts = await session.list_prompts()
|
||||
print("\nAvailable prompts:")
|
||||
for prompt in prompts.prompts:
|
||||
print(f" - {prompt.name}")
|
||||
|
||||
# Complete resource template arguments
|
||||
if templates.resourceTemplates:
|
||||
template = templates.resourceTemplates[0]
|
||||
print(f"\nCompleting arguments for resource template: {template.uriTemplate}")
|
||||
|
||||
# Complete without context
|
||||
result = await session.complete(
|
||||
ref=ResourceTemplateReference(type="ref/resource", uri=template.uriTemplate),
|
||||
argument={"name": "owner", "value": "model"},
|
||||
)
|
||||
print(f"Completions for 'owner' starting with 'model': {result.completion.values}")
|
||||
|
||||
# Complete with context - repo suggestions based on owner
|
||||
result = await session.complete(
|
||||
ref=ResourceTemplateReference(type="ref/resource", uri=template.uriTemplate),
|
||||
argument={"name": "repo", "value": ""},
|
||||
context_arguments={"owner": "modelcontextprotocol"},
|
||||
)
|
||||
print(f"Completions for 'repo' with owner='modelcontextprotocol': {result.completion.values}")
|
||||
|
||||
# Complete prompt arguments
|
||||
if prompts.prompts:
|
||||
prompt_name = prompts.prompts[0].name
|
||||
print(f"\nCompleting arguments for prompt: {prompt_name}")
|
||||
|
||||
result = await session.complete(
|
||||
ref=PromptReference(type="ref/prompt", name=prompt_name),
|
||||
argument={"name": "style", "value": ""},
|
||||
)
|
||||
print(f"Completions for 'style' argument: {result.completion.values}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Entry point for the completion client."""
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
85
examples/snippets/clients/stdio_client.py
Normal file
85
examples/snippets/clients/stdio_client.py
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
"""MCP client example using stdio transport.
|
||||
|
||||
This is a documentation example showing how to write an MCP client.
|
||||
cd to the `examples/snippets/clients` directory and run:
|
||||
uv run client
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from pydantic import AnyUrl
|
||||
|
||||
from mcp import ClientSession, StdioServerParameters, types
|
||||
from mcp.client.stdio import stdio_client
|
||||
from mcp.shared.context import RequestContext
|
||||
|
||||
# Create server parameters for stdio connection
|
||||
server_params = StdioServerParameters(
|
||||
command="uv", # Using uv to run the server
|
||||
args=["run", "server", "fastmcp_quickstart", "stdio"], # We're already in snippets dir
|
||||
env={"UV_INDEX": os.environ.get("UV_INDEX", "")},
|
||||
)
|
||||
|
||||
|
||||
# Optional: create a sampling callback
|
||||
async def handle_sampling_message(
|
||||
context: RequestContext, params: types.CreateMessageRequestParams
|
||||
) -> types.CreateMessageResult:
|
||||
print(f"Sampling request: {params.messages}")
|
||||
return types.CreateMessageResult(
|
||||
role="assistant",
|
||||
content=types.TextContent(
|
||||
type="text",
|
||||
text="Hello, world! from model",
|
||||
),
|
||||
model="gpt-3.5-turbo",
|
||||
stopReason="endTurn",
|
||||
)
|
||||
|
||||
|
||||
async def run():
|
||||
async with stdio_client(server_params) as (read, write):
|
||||
async with ClientSession(read, write, sampling_callback=handle_sampling_message) as session:
|
||||
# Initialize the connection
|
||||
await session.initialize()
|
||||
|
||||
# List available prompts
|
||||
prompts = await session.list_prompts()
|
||||
print(f"Available prompts: {[p.name for p in prompts.prompts]}")
|
||||
|
||||
# Get a prompt (greet_user prompt from fastmcp_quickstart)
|
||||
if prompts.prompts:
|
||||
prompt = await session.get_prompt("greet_user", arguments={"name": "Alice", "style": "friendly"})
|
||||
print(f"Prompt result: {prompt.messages[0].content}")
|
||||
|
||||
# List available resources
|
||||
resources = await session.list_resources()
|
||||
print(f"Available resources: {[r.uri for r in resources.resources]}")
|
||||
|
||||
# List available tools
|
||||
tools = await session.list_tools()
|
||||
print(f"Available tools: {[t.name for t in tools.tools]}")
|
||||
|
||||
# Read a resource (greeting resource from fastmcp_quickstart)
|
||||
resource_content = await session.read_resource(AnyUrl("greeting://World"))
|
||||
content_block = resource_content.contents[0]
|
||||
if isinstance(content_block, types.TextContent):
|
||||
print(f"Resource content: {content_block.text}")
|
||||
|
||||
# Call a tool (add tool from fastmcp_quickstart)
|
||||
result = await session.call_tool("add", arguments={"a": 5, "b": 3})
|
||||
result_unstructured = result.content[0]
|
||||
if isinstance(result_unstructured, types.TextContent):
|
||||
print(f"Tool result: {result_unstructured.text}")
|
||||
result_structured = result.structuredContent
|
||||
print(f"Structured tool result: {result_structured}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Entry point for the client script."""
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in a new issue