Skip to content

Commit d08e585

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

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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()

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)