|
| 1 | +""" |
| 2 | +cd to the `examples/snippets/clients` directory and run: |
| 3 | + uv run logging-client |
| 4 | +""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +import os |
| 8 | + |
| 9 | +from mcp import ClientSession, StdioServerParameters |
| 10 | +from mcp.client.stdio import stdio_client |
| 11 | +from mcp.types import LoggingMessageNotificationParams |
| 12 | + |
| 13 | +# Create server parameters for stdio connection |
| 14 | +server_params = StdioServerParameters( |
| 15 | + command="uv", # Using uv to run the server |
| 16 | + args=["run", "server", "logging", "stdio"], # We're already in snippets dir |
| 17 | + env={"UV_INDEX": os.environ.get("UV_INDEX", "")}, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +async def logging_callback(params: LoggingMessageNotificationParams): |
| 22 | + print(f"Log Level: {params.level}, Message: {params.data}") |
| 23 | + |
| 24 | + |
| 25 | +async def run(): |
| 26 | + fds = os.pipe() |
| 27 | + reader = os.fdopen(fds[0], "r") |
| 28 | + writer = os.fdopen(fds[1], "w") |
| 29 | + async with stdio_client(server_params, errlog=writer) as (read, write): |
| 30 | + async with ClientSession(read, write, logging_callback=logging_callback) as session: |
| 31 | + await session.initialize() |
| 32 | + |
| 33 | + await session.list_tools() |
| 34 | + await session.call_tool("log", arguments={}) |
| 35 | + writer.close() |
| 36 | + print("Captured stderr logs:") |
| 37 | + print(reader.read()) |
| 38 | + |
| 39 | + |
| 40 | +def main(): |
| 41 | + """Entry point for the client script.""" |
| 42 | + asyncio.run(run()) |
| 43 | + |
| 44 | + |
| 45 | +if __name__ == "__main__": |
| 46 | + main() |
0 commit comments