6.4 KiB
MCP OpenAI Client with Flexible Transport
A powerful Python client that integrates OpenAI models with MCP (Model Context Protocol) servers, supporting both SSE and stdio transport methods.
🌟 Features
- Flexible Transport: Choose between SSE and stdio transport methods
- OpenAI Integration: Seamlessly use GPT models with MCP tools
- Interactive Mode: Command-line interface for natural conversation
- Tool Execution: Automatic tool calling based on user queries
- Resource Support: Access to MCP resources and prompts
- Error Handling: Robust error handling and connection management
🚀 Quick Start
Prerequisites
-
OpenAI API Key: Set your OpenAI API key as an environment variable:
export OPENAI_API_KEY="your-api-key-here" -
MCP Server Running: Make sure your MCP server is running:
# For SSE transport (recommended) python run_mcp_server.py --transport sse # For stdio transport python run_mcp_server.py --transport stdio
Basic Usage
Interactive Mode (Recommended)
# Default: SSE transport, GPT-4o model
python mcp_openai_client.py
# Stdio transport
python mcp_openai_client.py --transport stdio
# Different model
python mcp_openai_client.py --model gpt-3.5-turbo
Single Query Mode
# Process a single query and exit
python mcp_openai_client.py --query "Calculate 15 + 27"
# With different transport
python mcp_openai_client.py --transport stdio --query "What's the square root of 144?"
Examples and Demos
# Run example scripts
python example_usage.py
📖 Usage Examples
SSE Transport (Default)
python mcp_openai_client.py
This will connect to http://localhost:8050/sse by default.
Custom Server URL
python mcp_openai_client.py --server-url http://localhost:3000/sse
Stdio Transport
python mcp_openai_client.py --transport stdio --server-script run_mcp_server.py
Different OpenAI Models
# GPT-3.5 Turbo (faster, cheaper)
python mcp_openai_client.py --model gpt-3.5-turbo
# GPT-4 (more capable)
python mcp_openai_client.py --model gpt-4
# GPT-4o (recommended default)
python mcp_openai_client.py --model gpt-4o
🔧 Available Tools
The client automatically discovers and uses all available MCP tools. Current tools include:
Math Tools
add- Add two numberssubtract- Subtract numbersmultiply- Multiply numbersdivide- Divide numberspower- Calculate powersquare_root- Calculate square rootcalculate_bmi- Calculate BMI
Text Tools
count_words- Count words in textsearch_text- Search for patternsreplace_text- Replace text patternsto_uppercase- Convert to uppercaseto_lowercase- Convert to lowercasetext_length- Get text length
System Tools
get_system_info- Get system informationget_current_time- Get current timelist_directory- List directory contentsget_file_info- Get file informationget_environment_variable- Get environment variables
Web Tools
url_encode- URL encode stringsurl_decode- URL decode stringsparse_url- Parse URLsvalidate_email- Validate email addressesextract_domain- Extract domains
Utility Tools
generate_greeting- Generate personalized greetings
📋 Available Resources
config://settings- Server configurationdynamic://greeting- Dynamic greeting resource
💬 Example Queries
Try these example queries to see the system in action:
- Math: "What is 123 multiplied by 456?"
- Text: "Count the words in this sentence and convert it to uppercase"
- System: "What time is it right now?"
- File: "List the contents of the current directory"
- Web: "Validate if 'user@example.com' is a valid email address"
- Combined: "Calculate the BMI for someone who is 5'10" tall and weighs 160 pounds, then tell me what time it is"
🏗️ Architecture
The client follows this workflow:
- Connection: Connects to MCP server using chosen transport (SSE/stdio)
- Discovery: Discovers available tools, prompts, and resources
- Query Processing: Sends user query to OpenAI with tool descriptions
- Tool Execution: If OpenAI requests tool use, executes tools via MCP
- Response: Returns final response incorporating tool results
🔧 Configuration
Environment Variables
OPENAI_API_KEY- Your OpenAI API key (required)
Command Line Options
--transport- Transport type:sse(default) orstdio--model- OpenAI model:gpt-4o(default),gpt-4,gpt-3.5-turbo--server-url- Server URL for SSE transport--server-script- Server script path for stdio transport--query- Single query to process--verbose- Enable verbose output
🚨 Troubleshooting
Connection Issues
- SSE Connection Failed: Make sure the MCP server is running with SSE transport
- Stdio Connection Failed: Check that the server script path is correct
- Port Issues: Ensure the server is running on the expected port (8050)
API Key Issues
- Missing API Key: Set the
OPENAI_API_KEYenvironment variable - Invalid API Key: Check that your OpenAI API key is valid and has credits
Tool Execution Issues
- Tool Not Found: The requested tool might not be available on the server
- Tool Execution Failed: Check the server logs for detailed error information
📝 Development
Adding New Tools
- Add your tool to the appropriate tool file in
src/mcp_template/tools/ - Follow the existing pattern with proper error handling
- Test the tool individually before integration
Modifying Transport Logic
The client supports both SSE and stdio transports. To add new transports:
- Add the transport type to the
TransportTypeenum - Implement the connection method in
MCPOpenAIClient - Update the
connect_to_servermethod
📄 License
This project is part of the MCP Template system. See the main README for licensing information.
🎯 Next Steps
-
Start the MCP Server:
python run_mcp_server.py --transport sse -
Set your OpenAI API Key:
export OPENAI_API_KEY="your-key-here" -
Run the Client:
python mcp_openai_client.py -
Ask Questions: Try queries like "Calculate 25 * 16" or "What tools do you have available?"
Enjoy using your MCP-powered OpenAI assistant! 🤖✨