Overview
The basic Python client demonstrates how to connect to an MCP server and interact with its capabilities using the officialmcp Python SDK. This client can list and execute tools, access resources, and use prompts.
Source Code
The implementation can be found at~/workspace/source/clients/basic-py/.
Installation
Using uv (Recommended)
Using pip
Project Configuration
Yourpyproject.toml should include:
Client Implementation
1. Imports
2. Server Configuration
Set up the connection parameters for the MCP server:3. Main Client Function
Create an async function to interact with the server:Working with MCP Capabilities
Listing and Using Prompts
Working with Resources
Listing and Executing Tools
Complete Example
Here’s the complete implementation from~/workspace/source/clients/basic-py/main.py:
Client API Methods
TheClientSession provides these key methods:
| Method | Description | Returns |
|---|---|---|
initialize() | Initializes the session | Coroutine |
list_prompts() | Lists all available prompts | PromptsListResult |
get_prompt(name, arguments) | Gets a prompt with arguments | PromptResult |
list_resources() | Lists all static resources | ResourcesListResult |
list_resource_templates() | Lists dynamic resource templates | ResourceTemplatesListResult |
read_resource(uri) | Reads a specific resource | ResourceResult |
list_tools() | Lists all available tools | ToolsListResult |
call_tool(name, arguments) | Executes a tool | ToolResult |
Context Managers
The Python client uses async context managers for proper resource management:Running the Client
With asyncio:
As a module:
Error Handling
Handle connection and execution errors:Type Hints
The MCP Python SDK includes full type hints for better IDE support:Next Steps
- Explore Python with Ollama integration
- Learn about TypeScript client implementation
- Build advanced MCP applications with LLMs