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
10 changes: 10 additions & 0 deletions mcp-client-python/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
# 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 output

`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 — the client counts the items it returns. 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/).

Requires the `mcp` 2.0 prereleases, so `pyproject.toml` sets `[tool.uv] prerelease = "allow"`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will remove this before un-drafting.

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
7 changes: 6 additions & 1 deletion mcp-client-python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ readme = "README.md"
requires-python = ">=3.10"
dependencies = [
"anthropic>=0.87.0",
"mcp>=1.28.1",
"mcp>=2.0.0b2",
"python-dotenv>=1.2.2",
]

Expand All @@ -15,6 +15,11 @@ dev = [
"ruff>=0.15.8",
]

# The 2026-07-28 protocol revision only ships in the mcp 2.0 prereleases, so
# allow them without every command needing --prerelease=allow.
[tool.uv]
prerelease = "allow"

[tool.ruff]
line-length = 120
target-version = "py310"
Expand Down
84 changes: 71 additions & 13 deletions mcp-client-python/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions weather-server-python/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
# A Simple MCP Weather Server written in Python

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

## Structured output

Both tools declare an output schema and return `structured_content`. `get_forecast` returns an object; `get_alerts` returns a top-level JSON array, which protocol revision `2026-07-28` is the first to allow — see [Structured Content](https://modelcontextprotocol.io/specification/draft/server/tools#structured-content) in the spec.

`Alerts` is a `RootModel[list[Alert]]` rather than a plain `list[Alert]` because the SDK wraps non-object return types as `{"result": ...}`; a `RootModel` is taken as the schema exactly as written. See [Structured Output](https://py.sdk.modelcontextprotocol.io/v2/servers/structured-output/) in the SDK docs.

Note that an array-rooted schema requires a `2026-07-28` client. This SDK does not project it down for older ones — it raises instead.

Requires the `mcp` 2.0 prereleases, so `pyproject.toml` sets `[tool.uv] prerelease = "allow"`.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will remove this before un-drafting.

10 changes: 8 additions & 2 deletions weather-server-python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ version = "0.1.0"
description = "A simple MCP weather server"
readme = "README.md"
requires-python = ">=3.10"
# httpx2 is a hard dependency of mcp, so it is not listed here — installing
# `mcp` already brings it in, and adding httpx would install a second HTTP stack.
dependencies = [
"httpx>=0.28.1",
"mcp[cli]>=1.26.0",
"mcp[cli]>=2.0.0b2",
]

[build-system]
Expand All @@ -18,6 +19,11 @@ dev = [
"ruff>=0.15.8",
]

# The 2026-07-28 protocol revision only ships in the mcp 2.0 prereleases, so
# allow them without every command needing --prerelease=allow.
[tool.uv]
prerelease = "allow"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will remove this before un-drafting.


[project.scripts]
weather = "weather:main"

Expand Down
Loading
Loading