|
| 1 | +""" |
| 2 | +Client example showing how to use async tools. |
| 3 | +
|
| 4 | +cd to the `examples/snippets` directory and run: |
| 5 | + uv run async-tools-client |
| 6 | + uv run async-tools-client --protocol=latest # backwards compatible mode |
| 7 | + uv run async-tools-client --protocol=next # async tools mode |
| 8 | +""" |
| 9 | + |
| 10 | +import asyncio |
| 11 | +import os |
| 12 | +import sys |
| 13 | + |
| 14 | +from mcp import ClientSession, StdioServerParameters, types |
| 15 | +from mcp.client.stdio import stdio_client |
| 16 | + |
| 17 | +# Create server parameters for stdio connection |
| 18 | +server_params = StdioServerParameters( |
| 19 | + command="uv", # Using uv to run the server |
| 20 | + args=["run", "server", "async_tools", "stdio"], |
| 21 | + env={"UV_INDEX": os.environ.get("UV_INDEX", "")}, |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +async def demonstrate_sync_tool(session: ClientSession): |
| 26 | + """Demonstrate calling a synchronous tool.""" |
| 27 | + print("\n=== Synchronous Tool Demo ===") |
| 28 | + |
| 29 | + result = await session.call_tool("sync_tool", arguments={"x": 21}) |
| 30 | + |
| 31 | + # Print the result |
| 32 | + for content in result.content: |
| 33 | + if isinstance(content, types.TextContent): |
| 34 | + print(f"Sync tool result: {content.text}") |
| 35 | + |
| 36 | + |
| 37 | +async def demonstrate_async_tool(session: ClientSession): |
| 38 | + """Demonstrate calling an async-only tool.""" |
| 39 | + print("\n=== Asynchronous Tool Demo ===") |
| 40 | + |
| 41 | + # Call the async tool |
| 42 | + result = await session.call_tool("async_only_tool", arguments={"data": "sample dataset"}) |
| 43 | + |
| 44 | + if result.operation: |
| 45 | + token = result.operation.token |
| 46 | + print(f"Async operation started with token: {token}") |
| 47 | + |
| 48 | + # Poll for status updates |
| 49 | + while True: |
| 50 | + status = await session.get_operation_status(token) |
| 51 | + print(f"Status: {status.status}") |
| 52 | + |
| 53 | + if status.status == "completed": |
| 54 | + # Get the final result |
| 55 | + final_result = await session.get_operation_result(token) |
| 56 | + for content in final_result.result.content: |
| 57 | + if isinstance(content, types.TextContent): |
| 58 | + print(f"Final result: {content.text}") |
| 59 | + break |
| 60 | + elif status.status == "failed": |
| 61 | + print(f"Operation failed: {status.error}") |
| 62 | + break |
| 63 | + elif status.status in ("canceled", "unknown"): |
| 64 | + print(f"Operation ended with status: {status.status}") |
| 65 | + break |
| 66 | + |
| 67 | + # Wait before polling again |
| 68 | + await asyncio.sleep(1) |
| 69 | + else: |
| 70 | + # Synchronous result (shouldn't happen for async-only tools) |
| 71 | + for content in result.content: |
| 72 | + if isinstance(content, types.TextContent): |
| 73 | + print(f"Unexpected sync result: {content.text}") |
| 74 | + |
| 75 | + |
| 76 | +async def demonstrate_hybrid_tool(session: ClientSession): |
| 77 | + """Demonstrate calling a hybrid tool in both modes.""" |
| 78 | + print("\n=== Hybrid Tool Demo ===") |
| 79 | + |
| 80 | + # Call hybrid tool (will be sync by default for compatibility) |
| 81 | + result = await session.call_tool("hybrid_tool", arguments={"message": "hello world"}) |
| 82 | + |
| 83 | + for content in result.content: |
| 84 | + if isinstance(content, types.TextContent): |
| 85 | + print(f"Hybrid tool result: {content.text}") |
| 86 | + |
| 87 | + |
| 88 | +async def demonstrate_batch_processing(session: ClientSession): |
| 89 | + """Demonstrate batch processing with progress updates.""" |
| 90 | + print("\n=== Batch Processing Demo ===") |
| 91 | + |
| 92 | + items = ["apple", "banana", "cherry", "date", "elderberry"] |
| 93 | + result = await session.call_tool("batch_operation_tool", arguments={"items": items}) |
| 94 | + |
| 95 | + if result.operation: |
| 96 | + token = result.operation.token |
| 97 | + print(f"Batch operation started with token: {token}") |
| 98 | + |
| 99 | + # Poll for status with progress tracking |
| 100 | + while True: |
| 101 | + status = await session.get_operation_status(token) |
| 102 | + print(f"Status: {status.status}") |
| 103 | + |
| 104 | + if status.status == "completed": |
| 105 | + # Get the final result |
| 106 | + final_result = await session.get_operation_result(token) |
| 107 | + |
| 108 | + # Check for structured result |
| 109 | + if final_result.result.structuredContent: |
| 110 | + print(f"Structured result: {final_result.result.structuredContent}") |
| 111 | + |
| 112 | + # Also show text content |
| 113 | + for content in final_result.result.content: |
| 114 | + if isinstance(content, types.TextContent): |
| 115 | + print(f"Text result: {content.text}") |
| 116 | + break |
| 117 | + elif status.status == "failed": |
| 118 | + print(f"Operation failed: {status.error}") |
| 119 | + break |
| 120 | + elif status.status in ("canceled", "unknown"): |
| 121 | + print(f"Operation ended with status: {status.status}") |
| 122 | + break |
| 123 | + |
| 124 | + # Wait before polling again |
| 125 | + await asyncio.sleep(0.5) |
| 126 | + else: |
| 127 | + print("Unexpected: batch operation returned synchronous result") |
| 128 | + |
| 129 | + |
| 130 | +async def demonstrate_data_processing(session: ClientSession): |
| 131 | + """Demonstrate complex data processing pipeline.""" |
| 132 | + print("\n=== Data Processing Pipeline Demo ===") |
| 133 | + |
| 134 | + operations = ["validate", "clean", "transform", "analyze", "export"] |
| 135 | + result = await session.call_tool( |
| 136 | + "data_processing_tool", arguments={"dataset": "customer_data.csv", "operations": operations} |
| 137 | + ) |
| 138 | + |
| 139 | + if result.operation: |
| 140 | + token = result.operation.token |
| 141 | + print(f"Data processing started with token: {token}") |
| 142 | + |
| 143 | + # Poll for completion |
| 144 | + while True: |
| 145 | + status = await session.get_operation_status(token) |
| 146 | + print(f"Status: {status.status}") |
| 147 | + |
| 148 | + if status.status == "completed": |
| 149 | + final_result = await session.get_operation_result(token) |
| 150 | + |
| 151 | + # Show structured result if available |
| 152 | + if final_result.result.structuredContent: |
| 153 | + print("Processing results:") |
| 154 | + for op, result_text in final_result.result.structuredContent.items(): |
| 155 | + print(f" {op}: {result_text}") |
| 156 | + break |
| 157 | + elif status.status == "failed": |
| 158 | + print(f"Processing failed: {status.error}") |
| 159 | + break |
| 160 | + elif status.status in ("canceled", "unknown"): |
| 161 | + print(f"Processing ended with status: {status.status}") |
| 162 | + break |
| 163 | + |
| 164 | + await asyncio.sleep(0.8) |
| 165 | + |
| 166 | + |
| 167 | +async def run(): |
| 168 | + """Run all async tool demonstrations.""" |
| 169 | + # Determine protocol version from command line |
| 170 | + protocol_version = "next" # Default to next for async tools |
| 171 | + if len(sys.argv) > 1: |
| 172 | + if "--protocol=latest" in sys.argv: |
| 173 | + protocol_version = "2025-06-18" # Latest stable protocol |
| 174 | + elif "--protocol=next" in sys.argv: |
| 175 | + protocol_version = "next" # Development protocol version with async tools |
| 176 | + |
| 177 | + print(f"Using protocol version: {protocol_version}") |
| 178 | + print() |
| 179 | + |
| 180 | + async with stdio_client(server_params) as (read, write): |
| 181 | + # Use configured protocol version |
| 182 | + async with ClientSession(read, write, protocol_version=protocol_version) as session: |
| 183 | + # Initialize the connection |
| 184 | + await session.initialize() |
| 185 | + |
| 186 | + # List available tools to see invocation modes |
| 187 | + tools = await session.list_tools() |
| 188 | + print("Available tools:") |
| 189 | + for tool in tools.tools: |
| 190 | + invocation_mode = getattr(tool, "invocationMode", "sync") |
| 191 | + print(f" - {tool.name}: {tool.description} (mode: {invocation_mode})") |
| 192 | + |
| 193 | + # Demonstrate different tool types |
| 194 | + await demonstrate_sync_tool(session) |
| 195 | + await demonstrate_hybrid_tool(session) |
| 196 | + await demonstrate_async_tool(session) |
| 197 | + await demonstrate_batch_processing(session) |
| 198 | + await demonstrate_data_processing(session) |
| 199 | + |
| 200 | + print("\n=== All demonstrations complete! ===") |
| 201 | + |
| 202 | + |
| 203 | +def main(): |
| 204 | + """Entry point for the async tools client.""" |
| 205 | + if "--help" in sys.argv or "-h" in sys.argv: |
| 206 | + print("Usage: async-tools-client [--protocol=latest|next]") |
| 207 | + print() |
| 208 | + print("Protocol versions:") |
| 209 | + print(" --protocol=latest Use stable protocol (only sync/hybrid tools visible)") |
| 210 | + print(" --protocol=next Use development protocol (all async tools visible)") |
| 211 | + print() |
| 212 | + print("Default: --protocol=next") |
| 213 | + return |
| 214 | + |
| 215 | + asyncio.run(run()) |
| 216 | + |
| 217 | + |
| 218 | +if __name__ == "__main__": |
| 219 | + main() |
0 commit comments