Skip to content

quiqupltd/example-client-mcp

Repository files navigation

Client MCP - OpenAI Agent with MCP Tool Access

A UV-based Python project that provides an OpenAI agent with access to BigQuery via MCP (Model Context Protocol) tools running on Google Cloud Run with IAM authentication.

Architecture

┌─────────────────┐
│  OpenAI Agent   │
│   (GPT-4)       │
└────────┬────────┘
         │
         │ Function Calling
         │
┌────────▼────────┐
│  MCP Client     │
│ (auth + HTTP)   │
└────────┬────────┘
         │
         │ IAM Auth + HTTPS
         │
┌────────▼────────────────────────────────────────┐
│  Cloud Run MCP Service                         │
│  https://bigquery-mcp-prod-729200795925...     │
│                                                 │
│  ┌──────────────┐                              │
│  │ BigQuery MCP │                              │
│  │    Tools     │                              │
│  └──────────────┘                              │
└─────────────────────────────────────────────────┘

Features

  • 🤖 OpenAI Agent: Uses GPT-4 with function calling for task automation
  • 🔐 IAM Authentication: Secure access to Cloud Run with automatic token refresh
  • 🛠️ MCP Integration: Automatic tool discovery and execution
  • 🐳 Docker Support: Complete Docker Compose setup for easy deployment
  • 🔄 Token Management: Automatic token refresh before expiration
  • 📝 Multiple Auth Methods: Supports ADC, service account keys, and Workload Identity

Prerequisites

  • Python 3.11+
  • UV: Fast Python package installer (Installation)
  • Docker & Docker Compose (for containerized deployment)
  • Google Cloud SDK (for authentication)
  • OpenAI API Key

Setup

1. Clone and Install Dependencies

# Navigate to project directory
cd client-mcp

# Install dependencies using UV
uv sync

2. Set Up Google Cloud Authentication

Option A: Application Default Credentials (ADC) - Recommended

# Authenticate with Google Cloud
gcloud auth application-default login

# Verify authentication
gcloud auth application-default print-access-token

Option B: Service Account Key File

  1. Create a service account in GCP Console
  2. Grant it the Cloud Run Invoker role
  3. Download the JSON key file
  4. Set environment variable:
export SERVICE_ACCOUNT_KEY_PATH=/path/to/key.json

Option C: Workload Identity (for GKE/Cloud Run)

See commented examples in src/auth_handler.py for detailed setup instructions.

3. Set OpenAI API Key

# Create .env file
echo "OPENAI_API_KEY=your-openai-api-key-here" > .env

Running the Application

Local Development (with UV)

# Activate virtual environment
source .venv/bin/activate

# Run the application
python src/main.py

# Or with a custom task
python src/main.py "Show me the schema of the users table"

Docker Compose (Recommended)

# Build and run
docker compose up

# Run in detached mode
docker compose up -d

# View logs
docker compose logs -f

# Stop
docker compose down

Docker Compose with Custom Task

Edit docker-compose.yml and modify the command:

command: python src/main.py "Your custom task here"

Usage Examples

Example 1: List Available Datasets

# In main.py, set task_description to:
"List all available BigQuery datasets and tables"

Example 2: Query Data

"Query the sales data for the last 30 days and provide a summary"

Example 3: Schema Inspection

"Show me the schema of the users table in the analytics dataset"

Example 4: Complex Analysis

"Analyze the top 10 products by revenue in Q4 and create a summary report with insights"

Project Structure

client-mcp/
├── pyproject.toml          # UV project configuration
├── docker-compose.yml      # Docker Compose configuration
├── Dockerfile              # Container image definition
├── .env                    # Environment variables (create this)
├── .gitignore             # Git ignore patterns
├── .dockerignore          # Docker ignore patterns
├── README.md              # This file
└── src/
    ├── __init__.py        # Package initialization
    ├── main.py            # Application entry point
    ├── auth_handler.py    # Cloud Run IAM authentication
    ├── mcp_client.py      # MCP protocol client
    └── agent.py           # OpenAI agent with tool calling

Authentication Methods

Method 1: Application Default Credentials (Primary)

Best for: Local development, GCE, Cloud Run, GKE

handler = CloudRunTokenHandler()

Setup:

gcloud auth application-default login

Method 2: Service Account Key File

Best for: CI/CD, specific service account requirements

handler = CloudRunTokenHandler(
    service_account_key_path="/path/to/key.json"
)

Setup:

  1. Create service account
  2. Grant roles/run.invoker
  3. Download JSON key
  4. Set SERVICE_ACCOUNT_KEY_PATH env var

Method 3: Workload Identity

Best for: Production deployments in GKE/Cloud Run

Automatically configured when running in GKE or Cloud Run with proper IAM bindings.

See src/auth_handler.py for detailed setup instructions with example YAML and commands.

Environment Variables

Variable Required Description
OPENAI_API_KEY Yes OpenAI API key for GPT-4 access
SERVICE_ACCOUNT_KEY_PATH No Path to service account JSON key (for Method 2)
GOOGLE_APPLICATION_CREDENTIALS No Path to credentials file (auto-detected)

Troubleshooting

Authentication Errors

Problem: "Failed to obtain valid credentials"

Solutions:

  1. Run gcloud auth application-default login
  2. Check if service account has roles/run.invoker permission
  3. Verify GOOGLE_APPLICATION_CREDENTIALS points to valid file
  4. Ensure Docker has access to credentials (check volume mounts)

MCP Service Unreachable

Problem: "MCP service health check failed"

Solutions:

  1. Verify Cloud Run service URL is correct
  2. Check network connectivity
  3. Ensure service account has proper permissions
  4. Check Cloud Run service is deployed and running

Token Refresh Issues

Problem: "Failed to refresh token"

Solutions:

  1. Re-authenticate: gcloud auth application-default login
  2. Check token hasn't been revoked
  3. Verify service account key is still valid
  4. Check system clock is synchronized

OpenAI API Errors

Problem: "OpenAI API key not set" or rate limit errors

Solutions:

  1. Verify .env file exists with OPENAI_API_KEY
  2. Check API key is valid at platform.openai.com
  3. Ensure you have sufficient credits/quota
  4. Implement rate limiting if needed

Development

Adding Dependencies

# Add to pyproject.toml first
# Then sync
uv sync

Running Tests (Future)

# Install dev dependencies
uv sync --dev

# Run tests
pytest

Code Quality

# Format code
ruff format .

# Lint code
ruff check .

Security Notes

  • Never commit .env files or service account keys to version control
  • Rotate service account keys regularly
  • Use least-privilege IAM roles
  • Enable audit logging for Cloud Run access
  • Use Workload Identity in production when possible

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

License

MIT License - see LICENSE file for details

Support

For issues and questions:

  • Check the troubleshooting section above
  • Review commented examples in source code
  • Open an issue on GitHub

Acknowledgments

  • Built with UV for fast Python package management
  • Uses OpenAI's function calling API
  • Implements MCP (Model Context Protocol)
  • Secured with Google Cloud IAM

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published