Skip to main content

Overview

The basic Python client demonstrates how to connect to an MCP server and interact with its capabilities using the official mcp 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 pip

Project Configuration

Your pyproject.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

The ClientSession provides these key methods:

Context Managers

The Python client uses async context managers for proper resource management:
This ensures that connections are properly closed even if errors occur.

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