MCP Python Server & Client
This server provides mathematical calculations, string manipulations, simulated weather data, file system access, system information, and prompt templates for LLMs.
Calculate (
calculate): Perform arithmetic operations — addition, subtraction, multiplication, division, power, square root, and modulo — with division-by-zero protection.String Operations (
string_operation): Manipulate text by reversing, counting words, changing case (uppercase/lowercase/title), counting characters, replacing substrings, or truncating.Get Weather (
get_weather): Retrieve simulated current weather or a 1–7 day forecast for any city.File Reader (
file://read/{path}): Read files securely by relative path, with path traversal prevention.File Listing (
file://list): List available files in the data directory.System Info (
system://info): Get full system details — platform, Python version, CPU, memory, and disk usage — as JSON.Platform Info (
system://platform): Get OS/platform-specific information.Code Review Prompt (
code_review): Generate a structured LLM prompt for reviewing code, with configurable language and focus areas.Summarization Prompt (
summarize_text): Generate an LLM prompt for summarizing text, with configurable max length and style.
The server also includes YAML-based configuration with environment variable overrides, structured logging, input validation, rate limiting, and comprehensive error handling.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MCP Python Server & Clientcalculate 12 * 8"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MCP Python Server & Client
A comprehensive implementation of the Model Context Protocol (MCP) in Python, demonstrating all core MCP components including tools, resources, prompts, and transports. This project serves as both a reference implementation and a learning resource for building MCP-based applications.
Objectives
Understand the Model Context Protocol (MCP) architecture and how it standardizes LLM-application integration
Build MCP servers that expose tools, resources, and prompts through a unified protocol interface
Implement MCP clients that discover server capabilities and invoke them programmatically
Design tool integrations that allow LLMs to execute functions with validated inputs and structured outputs
Apply the server/client communication pattern using stdio transport for inter-process MCP messaging
Create shared context resources that provide LLMs with access to files, system data, and dynamic information
Develop reusable prompt templates that structure LLM interactions for consistent, high-quality outputs
Implement security best practices including input validation, rate limiting, and path traversal prevention in MCP servers
Configure MCP applications externally using YAML settings with environment variable overrides for deployment flexibility
Write comprehensive test suites for MCP components covering unit, integration, and async patterns
Related MCP server: MCP Demo Server
Table of Contents
Project Overview
The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to Large Language Models (LLMs). This project implements:
MCP Server — Exposes tools (executable functions), resources (data endpoints), and prompts (reusable templates) via the MCP protocol over stdio transport
MCP Client — Connects to the server, discovers capabilities, and invokes tools/resources/prompts
Full Infrastructure — Configuration management, structured logging, input validation, rate limiting, and comprehensive error handling
Key Features
3 tools: Calculator, String Utilities, Weather (simulated)
4 resources: File Reader (secure), System Info, Platform Info, File Listing
2 prompts: Code Review, Text Summarization
Configurable via external YAML with environment variable overrides
Log levels (DEBUG/INFO/WARNING/ERROR/CRITICAL) controllable via settings file
Security hardening: path traversal prevention, input sanitization, rate limiting
230 automated tests (unit + integration) with pytest
Architecture
The project follows a layered architecture with clear separation of concerns:
┌─────────────────────────────────────────────────────────┐
│ MCP Client │
│ (connects via stdio, calls tools/resources/prompts) │
└─────────────────────┬───────────────────────────────────┘
│ stdio transport
┌─────────────────────▼───────────────────────────────────┐
│ MCP Server (FastMCP) │
├─────────────┬───────────────────┬───────────────────────┤
│ Tools │ Resources │ Prompts │
│ ─────────── │ ───────────────── │ ───────────────────── │
│ Calculator │ File Reader │ Code Review │
│ String Ops │ System Info │ Summarization │
│ Weather │ │ │
├─────────────┴───────────────────┴───────────────────────┤
│ Core Infrastructure │
│ Config Loader │ Logger │ Validator │ Rate Limiter │
├─────────────────────────────────────────────────────────┤
│ Exception Hierarchy │
└─────────────────────────────────────────────────────────┘Project Structure
ai-genai-mcp/
├── config/
│ └── settings.yaml # All environment-specific configuration
├── src/
│ ├── __init__.py # Package root
│ ├── config/
│ │ ├── __init__.py
│ │ └── config_loader.py # YAML loading + Pydantic validation + env overrides
│ ├── utils/
│ │ ├── __init__.py
│ │ ├── exceptions.py # Custom exception hierarchy (7 types)
│ │ ├── logger.py # Rotating file + console logging with sanitization
│ │ ├── validator.py # Input validation and security sanitization
│ │ └── rate_limiter.py # Token bucket rate limiter
│ ├── server/
│ │ ├── __init__.py
│ │ ├── main.py # Server entry point and assembly
│ │ ├── tools/
│ │ │ ├── __init__.py
│ │ │ ├── calculator.py # Math operations tool
│ │ │ ├── string_utils.py # Text manipulation tool
│ │ │ └── weather.py # Simulated weather API tool
│ │ ├── resources/
│ │ │ ├── __init__.py
│ │ │ ├── file_reader.py # Secure file reading resource
│ │ │ └── system_info.py # System metrics resource
│ │ └── prompts/
│ │ ├── __init__.py
│ │ ├── code_review.py # Code review prompt template
│ │ └── summarization.py # Text summarization prompt template
│ └── client/
│ ├── __init__.py
│ ├── main.py # Client entry point
│ ├── mcp_client.py # High-level client wrapper
│ └── interactive_demo.py # Feature demonstration runner
├── tests/
│ ├── conftest.py # Shared test fixtures
│ ├── unit/ # 223 unit tests
│ │ ├── test_calculator.py
│ │ ├── test_string_utils.py
│ │ ├── test_weather.py
│ │ ├── test_file_reader.py
│ │ ├── test_system_info.py
│ │ ├── test_code_review_prompt.py
│ │ ├── test_summarization_prompt.py
│ │ ├── test_config_loader.py
│ │ ├── test_logger.py
│ │ ├── test_validator.py
│ │ ├── test_rate_limiter.py
│ │ └── test_exceptions.py
│ └── integration/ # 7 integration tests
│ └── test_client_server.py
├── pyproject.toml # Project metadata and dependencies
├── requirements.txt # Production dependencies
├── requirements-dev.txt # Development dependencies
├── .gitignore # Git ignore patterns
└── README.md # This fileDependencies
Package | Version | Purpose |
| >=1.27.2 | Official MCP SDK (server + client + transports) |
| >=6.0.2 | YAML configuration file parsing |
| >=2.7.0 | Configuration validation and type safety |
| >=8.2.0 | Testing framework (dev) |
| >=0.23.0 | Async test support (dev) |
| >=5.0.0 | Test coverage reporting (dev) |
| >=0.4.0 | Linting and formatting (dev) |
Deployment
Prerequisites
Python 3.10 or higher
pip package manager
git (for cloning the repository)
Verify your Python version:
python --version # Must be 3.10+Installation
Clone the repository:
git clone <repository-url>
cd ai-genai-mcpCreate a virtual environment (recommended):
python -m venv .venv
source .venv/bin/activate # Linux/Mac
.venv\Scripts\activate # WindowsInstall the package with dependencies:
# Production only
pip install -e .
# With development tools (testing, linting)
pip install -e ".[dev]"Running the Server
Start the MCP server using stdio transport (default):
# Using the installed entry point
mcp-server
# Or using Python module syntax
python -m src.server.main
# With custom config file
python -m src.server.main --config /path/to/settings.yamlThe server will listen on stdio and is ready to accept MCP client connections.
Running the Client
The client connects to the server via stdio and runs an interactive demo:
# Using the installed entry point
mcp-client
# Or using Python module syntax
python -m src.client.main
# With custom config file
python -m src.client.main --config /path/to/settings.yamlRunning Tests
# Run all tests
python -m pytest
# Run only unit tests
python -m pytest tests/unit/ -v
# Run only integration tests
python -m pytest tests/integration/ -v
# Run with coverage report
python -m pytest tests/unit/ --cov=src --cov-report=term-missing
# Run linting
ruff check src/ tests/External Configuration
Settings File
All environment-specific configuration is in config/settings.yaml. This is the single source of truth for runtime behavior. Key sections:
Section | Purpose |
| Host, port, name, transport, timeouts |
| Server URL, retries, timeouts |
| Level, file path, rotation, format |
| Rate limits, payload limits, CORS origins |
| Calculator precision, API URLs/keys, string limits |
| Base directory, file size limits, allowed extensions |
Environment Variable Overrides
Any YAML setting can be overridden via environment variables using the convention:
MCP_<SECTION>_<KEY>=valueExamples:
# Override log level
export MCP_LOGGING_LEVEL=DEBUG
# Override server port
export MCP_SERVER_PORT=9090
# Override rate limit
export MCP_SECURITY_RATE_LIMIT_PER_MINUTE=120
# Set weather API key (secrets should always use env vars)
export MCP_TOOLS_WEATHER_API_KEY=your-real-key-hereEnvironment variables take precedence over YAML file values.
Logging Configuration
Log levels are controlled via config/settings.yaml under the logging section:
logging:
level: "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL
file_path: "logs/mcp_application.log"
max_file_size_bytes: 10485760 # 10 MB rotation
backup_count: 5 # Keep 5 rotated files
console_output: true # Also print to stderrOr override at runtime:
MCP_LOGGING_LEVEL=DEBUG python -m src.server.mainLog output is automatically sanitized — passwords, API keys, tokens, and secrets are replaced with [REDACTED] in log files.
End-to-End Flow Diagram
sequenceDiagram
participant Client as MCP Client
participant Transport as Stdio Transport
participant Server as MCP Server
participant Tools as Tool Handlers
participant Resources as Resource Handlers
participant Prompts as Prompt Handlers
participant Config as Config Loader
participant Validator as Input Validator
participant RateLimiter as Rate Limiter
Note over Config: Application Startup
Config->>Config: Load settings.yaml
Config->>Config: Apply env var overrides
Config->>Config: Validate with Pydantic
Note over Server: Server Initialization
Server->>Config: Get server config
Server->>Tools: Register calculator, string, weather
Server->>Resources: Register file reader, system info
Server->>Prompts: Register code review, summarization
Note over Client,Server: Client Connection
Client->>Transport: Connect via stdio
Transport->>Server: Initialize protocol
Server-->>Client: Server capabilities
Note over Client,Tools: Tool Invocation
Client->>Server: call_tool("calculate", {op: "add", a: 5, b: 3})
Server->>RateLimiter: Check rate limit
RateLimiter-->>Server: Allowed
Server->>Validator: Validate inputs
Validator-->>Server: Valid
Server->>Tools: Execute calculator.add(5, 3)
Tools-->>Server: Result: 8.0
Server-->>Client: "Result: 8.0"
Note over Client,Resources: Resource Reading
Client->>Server: read_resource("system://info")
Server->>Resources: Get system information
Resources-->>Server: JSON system data
Server-->>Client: System info JSON
Note over Client,Prompts: Prompt Retrieval
Client->>Server: get_prompt("code_review", {code: "...", language: "python"})
Server->>Validator: Validate code input
Validator-->>Server: Valid
Server->>Prompts: Build prompt messages
Prompts-->>Server: [system_msg, user_msg]
Server-->>Client: Structured prompt messagesComponents Reference
Tools
Tool | Operation | Description |
|
| Add two numbers |
|
| Subtract second from first |
|
| Multiply two numbers |
|
| Divide first by second (guards against /0) |
|
| Raise base to exponent |
|
| Square root (non-negative only) |
|
| Remainder of division |
|
| Reverse character order |
|
| Count words in text |
|
| Convert to uppercase |
|
| Convert to lowercase |
|
| Capitalize first letters |
|
| Count letters, digits, spaces |
|
| Replace substring (extra: "old|new") |
|
| Truncate to length with suffix |
| current | Get current weather for a city |
| forecast | Get 1-7 day forecast |
Resources
URI | Description |
| Full system info (platform, Python, memory, disk, CPU) |
| OS and platform details only |
| List available files in data directory |
| Read a file by relative path (security validated) |
Prompts
Name | Arguments | Description |
|
| Generates a structured code review prompt |
|
| Generates a text summarization prompt |
Security
This implementation includes multiple security layers:
Path Traversal Prevention — File paths are resolved and validated against the base directory;
../sequences and null bytes are blockedInput Sanitization — Control characters and null bytes are stripped from all external input
Input Length Limits — Configurable maximum lengths prevent memory exhaustion
Rate Limiting — Token bucket algorithm limits requests per client per minute
Extension Whitelist — Only configured file extensions can be accessed
Payload Size Limits — Maximum request payload size is enforced
Log Sanitization — Passwords, API keys, and tokens are automatically redacted in logs
No Dynamic Code Execution — No
eval(),exec(), or dynamic imports
Contributing
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Write tests for your changes
Ensure all tests pass (
python -m pytest)Ensure code passes linting (
ruff check src/ tests/)Commit your changes
Push to the branch
Open a Pull Request
Available Tools
3 toolscalculateA
Perform a mathematical calculation.
Args: operation: The math operation (add, subtract, multiply, divide, power, sqrt, modulo) a: The first number b: The second number (not used for sqrt)
Returns: The calculation result as a string
| Name | Required | Description | Default |
|---|---|---|---|
| a | Yes | ||
| b | No | ||
| operation | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries full burden. It specifies operations, parameter roles (a, b, operation), and return type (string). Missing details on error handling or edge cases, but adequate for a calculator.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Reasonably concise with clear docstring format. Each sentence adds value, though could be slightly more streamlined.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Tool is simple; description covers parameters and return. No output schema details needed as description already states return type. Adequate for its complexity.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 0%, but the description compensates fully by explaining each parameter's role: operation as math operation, a as first number, b as second number (with note for sqrt). Adds meaning beyond schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description explicitly states it performs mathematical calculations, lists supported operations, and clearly distinguishes from siblings like get_weather and string_operation.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No explicit guidance on when to use this tool versus alternatives or when not to use it. Sibling tools are unrelated, but usage context is not addressed.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_weatherA
Get current weather or forecast for a city.
Args: city: The city name to get weather for forecast_days: Number of days for forecast (0 for current weather only, max 7)
Returns: Weather information as a formatted string
| Name | Required | Description | Default |
|---|---|---|---|
| city | Yes | ||
| forecast_days | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries full burden. It states the return is a formatted string, but does not disclose potential side effects, required authentication, rate limits, or caching behavior. For a simple read operation this is acceptable but could be improved.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise with no wasted words. It uses a clear structure with Args and Returns sections, front-loading the core purpose. Every sentence adds value.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple with two parameters and an existing output schema. The description covers the main functionality and return format. Minor omissions like units or timezone could be added, but the description is largely complete for an agent to use correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, but the description adds thorough meaning: 'city' is clearly defined as the city name, and 'forecast_days' includes its purpose, default behavior (0 for current weather), and maximum value (7). This exceeds what the schema provides.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description explicitly states it gets current weather or forecast for a city, providing a specific verb and resource. It is clearly distinct from sibling tools (calculate, string_operation) which have no weather-related functionality.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description clearly indicates when to use the tool (to get weather information) and the parameters control current vs forecast. While it does not explicitly state when not to use it, the context is straightforward and alternatives are unnecessary given the distinct sibling tools.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
string_operationA
Perform a string manipulation operation.
Args: operation: The string operation (reverse, count_words, uppercase, lowercase, title_case, count_chars, replace, truncate) text: The input text to operate on extra: Extra parameter (replacement text for 'replace', or max length for 'truncate')
Returns: The operation result as a string
| Name | Required | Description | Default |
|---|---|---|---|
| text | Yes | ||
| extra | No | ||
| operation | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the burden. It mentions the return type (string) but does not disclose any behavioral traits like side effects, state changes, or error handling. As a pure string manipulation function, it is safe, but transparency is minimal.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is structured as a docstring with Args and Returns sections, making it easy to parse. It is front-loaded with the purpose. Slightly verbose for the simple nature of the tool, but acceptable.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given no annotations and no schema descriptions, the description covers the purpose, all parameters, and return value. It is fairly complete for a pure function tool. Missing context: behavior with invalid operations and potential errors.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It explains the 'operation' parameter with enumerated values, 'text' as input, and 'extra' with usage for replace (replacement text) and truncate (max length). This adds significant meaning beyond the schema. However, it could clarify that 'extra' is ignored for other operations.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states it performs string manipulation operations and lists specific operations like reverse, count_words, etc. It is a specific verb+resource that distinguishes from sibling tools (calculate, get_weather) which are unrelated.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description lists available operations and explains parameters, providing implied usage context. However, it does not explicitly state when to use this tool vs alternatives or provide conditions for use.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v1.0.0- First observed
calculate - First observed
get_weather - First observed
string_operation
TDQS
Scored across 3 tools
Each tool has a unique domain: math, weather, and string operations. There is no overlap or ambiguity in their purposes.
All tools follow a consistent verb_noun pattern (calculate, get_weather, string_operation), making them predictable and easy to understand.
The server has only 3 tools, which is on the thin side but acceptable for a focused utility server. Each tool serves a distinct purpose.
The tools cover basic math, weather, and string operations. Minor gaps exist (e.g., no advanced math or weather forecast details), but the set is sufficient for common tasks.
Maintenance
Related MCP Connectors
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
Security scanner for MCP servers. Detect vulnerabilities, prompt injection, and tool poisoning.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Hosted MCP server to manage a restaurant menu from AI agents - 39 tools over the DuckHub API.
Related MCP Servers
- FlicenseBqualityDmaintenanceProvides a complete end-to-end MCP server implementation with file system tools, web scraping capabilities, and system information access. Includes ready-to-use configuration files and integration examples for Claude Desktop, ChatGPT, and other AI models.6-
- AlicenseNot gradedqualityDmaintenanceA demonstration MCP server showcasing tools (calculator, file operations, weather, timestamp), resources (server config, system info, documentation), and reusable prompt templates for code review, documentation, and debugging.Apache 2.0
- AlicenseBqualityDmaintenanceA comprehensive MCP server with 30+ custom tools organized into categories: date/time operations, file management, system information, text processing, and web operations. Enables async communication with robust error handling and flexible CLI integration.311MIT
- FlicenseNot gradedqualityCmaintenanceA production-ready MCP server providing file, system, math, and text utilities through a simple CLI client.-