Skip to content

Commit e2e3ddd

Browse files
Merge pull request #825 from realpython/update-mcp-client-sdk-v2
Update python-mcp-client sample code for MCP SDK 2.x
2 parents ef980c8 + fd8a820 commit e2e3ddd

7 files changed

Lines changed: 405 additions & 293 deletions

File tree

‎python-mcp-client/source-code-final/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ $ uv run python -m mcp_client <path/to/mcp/server.py> --chat
5050
```console
5151
$ uv run python -m mcp_client mcp_server/mcp_server.py --chat
5252

53-
MCP Client Started!
53+
MCP Client's Chat Started!
5454
Type your queries or 'quit' to exit.
5555

5656
You: Greet Pythonista
@@ -68,14 +68,14 @@ You:
6868

6969
The project includes, `mcp_server.py`, which is a minimal MCP server that provides:
7070

71-
- A sample tool that says hello
71+
- A sample `echo` tool that echoes back a message
7272
- Sample prompts and resources
7373

7474
You can use this server to test the client's functionalities.
7575

7676
## Requirements
7777

78-
- Python >= 3.13
78+
- Python >= 3.14
7979
- The MCP Python SDK and OpenAI Python SDK
8080
- An OpenAI API key
8181
- An MCP server to connect to

‎python-mcp-client/source-code-final/mcp_client/chat.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ async def run_chat(handler) -> None:
1111
break
1212

1313
print("\n" + await handler.process_query(query))
14+
except EOFError:
15+
break
1416
except Exception as e:
1517
print(f"\nError: {str(e)}")
1618

‎python-mcp-client/source-code-final/mcp_client/handlers.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from mcp import ClientSession
55
from openai import OpenAI
66

7-
MODEL = "gpt-4o-mini"
7+
MODEL = "gpt-5.4-mini"
88
MAX_TOKENS = 1000
99

1010

@@ -25,7 +25,7 @@ async def process_query(self, query: str) -> str:
2525
messages = [{"role": "user", "content": query}]
2626
initial_response = self.openai.chat.completions.create(
2727
model=MODEL,
28-
max_tokens=MAX_TOKENS,
28+
max_completion_tokens=MAX_TOKENS,
2929
messages=messages,
3030
tools=await self._get_tools(),
3131
)
@@ -55,7 +55,7 @@ async def process_query(self, query: str) -> str:
5555
# Get final Model's response after tool execution
5656
final_response = self.openai.chat.completions.create(
5757
model=MODEL,
58-
max_tokens=MAX_TOKENS,
58+
max_completion_tokens=MAX_TOKENS,
5959
messages=messages,
6060
)
6161

@@ -75,7 +75,7 @@ async def _get_tools(self) -> list:
7575
"description": tool.description or "No description",
7676
"parameters": getattr(
7777
tool,
78-
"inputSchema",
78+
"input_schema",
7979
{"type": "object", "properties": {}},
8080
),
8181
},

‎python-mcp-client/source-code-final/mcp_client/mcp_client.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
import sys
23
from contextlib import AsyncExitStack
34
from typing import Any, Awaitable, Callable, ClassVar, Self
@@ -36,13 +37,11 @@ async def _connect_to_server(self) -> ClientSession:
3637
read, write = await self.exit_stack.enter_async_context(
3738
stdio_client(
3839
server=StdioServerParameters(
39-
command="sh",
40-
args=[
41-
"-c",
42-
f"{sys.executable} {self.server_path} 2>/dev/null",
43-
],
40+
command=sys.executable,
41+
args=[self.server_path],
4442
env=None,
45-
)
43+
),
44+
errlog=open(os.devnull, "w"),
4645
)
4746
)
4847
client_session = await self.exit_stack.enter_async_context(

‎python-mcp-client/source-code-final/mcp_server/mcp_server.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
from mcp.server.fastmcp import FastMCP
1+
from pathlib import Path
22

3-
mcp = FastMCP("mcp_server")
3+
from mcp.server.mcpserver import MCPServer
4+
5+
mcp = MCPServer("mcp_server")
46

57

68
@mcp.tool()
@@ -12,13 +14,14 @@ async def echo(message: str) -> str:
1214
@mcp.prompt()
1315
async def greeting_prompt(name: str) -> str:
1416
"""A simple greeting prompt."""
15-
return f"Great {name} kindly."
17+
return f"Greet {name} kindly."
1618

1719

1820
@mcp.resource("file://./greeting.txt")
1921
def greeting_file() -> str:
2022
"""The greeting text file."""
21-
with open("greeting.txt", "r", encoding="utf-8") as file:
23+
path = Path(__file__).parent / "greeting.txt"
24+
with open(path, "r", encoding="utf-8") as file:
2225
return file.read()
2326

2427

‎python-mcp-client/source-code-final/pyproject.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ description = "MCP client for testing MCP servers."
55
readme = "README.md"
66
requires-python = ">=3.14"
77
dependencies = [
8-
"mcp>=1.20.0",
9-
"openai>=2.6.1",
8+
"mcp>=2.2.0,<3.0",
9+
"openai>=3.16.2,<4.0",
1010
]
1111

1212
[project.scripts]

0 commit comments

Comments
 (0)