Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions mcp-client-python/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# An LLM-Powered Chatbot MCP Client written in Python

See the [Build an MCP client](https://modelcontextprotocol.io/docs/develop/build-client) tutorial for more information.

## Structured content

`call_tool` validates every result against the tool's declared output schema, so the spec's client-side SHOULD needs no code here.

The two channels go to different readers: `content` is forwarded to the model, while `structured_content` is used as data — when a tool returns an array, the client counts its items rather than re-reading the prose. See [Structured Content](https://modelcontextprotocol.io/specification/draft/server/tools#structured-content).

`Client(transport, mode="auto")` probes `server/discover` and falls back to the `2025-11-25` handshake; `client.protocol_version` reports which era you got. See [Protocol versions](https://py.sdk.modelcontextprotocol.io/v2/protocol-versions/).
41 changes: 26 additions & 15 deletions mcp-client-python/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,21 @@

from anthropic import Anthropic
from dotenv import load_dotenv
from mcp import ClientSession, StdioServerParameters
from mcp import Client, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp_types import TextContent

load_dotenv() # load environment variables from .env

# Claude model constant
ANTHROPIC_MODEL = "claude-sonnet-4-5"
ANTHROPIC_MODEL = "claude-sonnet-5"
MAX_TOOL_TURNS = 10


class MCPClient:
def __init__(self):
# Initialize session and client objects
self.session: ClientSession | None = None
self.client: Client | None = None
self.exit_stack = AsyncExitStack()
self._anthropic: Anthropic | None = None

Expand Down Expand Up @@ -50,24 +51,23 @@ async def connect_to_server(self, server_script_path: str):
else:
server_params = StdioServerParameters(command="node", args=[server_script_path], env=None)

stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
self.stdio, self.write = stdio_transport
self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))

await self.session.initialize()
# "auto" probes server/discover, falling back to the 2025-11-25 handshake.
self.client = await self.exit_stack.enter_async_context(
Client(stdio_client(server_params), mode="auto")
)

# List available tools
response = await self.session.list_tools()
response = await self.client.list_tools()
tools = response.tools
print("\nConnected to server with tools:", [tool.name for tool in tools])
print(f"\nConnected over protocol {self.client.protocol_version} with tools:", [tool.name for tool in tools])

async def process_query(self, query: str) -> str:
"""Process a query using Claude and available tools"""
messages = [{"role": "user", "content": query}]

tools_response = await self.session.list_tools()
tools_response = await self.client.list_tools()
available_tools = [
{"name": tool.name, "description": tool.description, "input_schema": tool.inputSchema}
{"name": tool.name, "description": tool.description, "input_schema": tool.input_schema}
for tool in tools_response.tools
]

Expand All @@ -90,13 +90,23 @@ async def process_query(self, query: str) -> str:

tool_results = []
for tool_use in tool_uses:
result = await self.session.call_tool(tool_use.name, tool_use.input)
# call_tool validates the result against the declared schema.
result = await self.client.call_tool(tool_use.name, tool_use.input)
final_text.append(f"[Calling tool {tool_use.name} with args {tool_use.input}]")

# structured_content is data the application can use directly.
if isinstance(result.structured_content, list):
final_text.append(f"[{tool_use.name} returned {len(result.structured_content)} items]")

# content is a list of block types; forward only the text ones.
tool_results.append(
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": result.content,
"content": "\n".join(
block.text for block in result.content if isinstance(block, TextContent)
),
"is_error": bool(result.is_error),
}
)

Expand All @@ -119,8 +129,9 @@ async def chat_loop(self):
print("Type your queries or 'quit' to exit.")

while True:
# input() blocks, so keep it off the event loop.
try:
query = input("\nQuery: ").strip()
query = (await asyncio.to_thread(input, "\nQuery: ")).strip()
except (EOFError, KeyboardInterrupt):
break

Expand Down
4 changes: 3 additions & 1 deletion mcp-client-python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"anthropic>=0.87.0",
"mcp>=1.28.1",
"mcp>=2.0.0",
# client.py imports TextContent from mcp_types, which `mcp` pins exactly.
"mcp-types>=2.0.0",
"python-dotenv>=1.2.2",
]
Comment on lines 7 to 13

Expand Down
Loading
Loading