Skip to content

Commit f157245

Browse files
committed
feat(client): add snippets for stderr and logging
1 parent b714324 commit f157245

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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(
31+
read, write, logging_callback=logging_callback
32+
) as session:
33+
await session.initialize()
34+
35+
await session.list_tools()
36+
await session.call_tool("log", arguments={})
37+
writer.close()
38+
print("Captured stderr logs:")
39+
print(reader.read())
40+
41+
42+
def main():
43+
"""Entry point for the client script."""
44+
asyncio.run(run())
45+
46+
47+
if __name__ == "__main__":
48+
main()

examples/snippets/pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,4 @@ direct-execution-server = "servers.direct_execution:main"
2222
display-utilities-client = "clients.display_utilities:main"
2323
oauth-client = "clients.oauth_client:run"
2424
elicitation-client = "clients.url_elicitation_client:run"
25+
logging-client = "clients.logging_client:main"
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
FastMCP Echo Server that sends log messages and prints to stderr
3+
"""
4+
5+
import sys
6+
7+
from mcp.server.fastmcp import Context, FastMCP
8+
9+
mcp = FastMCP("Logging and stdio test")
10+
11+
12+
@mcp.tool()
13+
async def log(ctx: Context) -> str:
14+
await ctx.debug("Debug message")
15+
await ctx.info("Info message")
16+
print("Stderr message", file=sys.stderr)
17+
await ctx.warning("Warning message")
18+
await ctx.error("Error message")
19+
return "done"
20+
21+
22+
if __name__ == "__main__":
23+
mcp.run(transport="stdio")

0 commit comments

Comments
 (0)