gp-connect-mcp-server

rbade1234/gp-connect-mcp-server

3.2

If you are the rightful owner of gp-connect-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

The GP Connect MCP Server is a comprehensive implementation of the GP Connect API, integrating FastAPI and MCP server for LLM agents, ensuring FHIR STU3 compliance and Azure deployment readiness.

Tools
11
Resources
0
Prompts
0

GP Connect MCP Server

A comprehensive GP Connect API implementation with FastAPI web server and MCP (Model Context Protocol) server integration for LLM agents. This project provides automatic JWT token generation, complete FHIR STU3 compliance, and production-ready GP Connect integration with Azure deployment support.

šŸš€ Features

Core Functionality

  • Complete GP Connect API Coverage: Foundations and Appointment Management APIs
  • Automatic JWT Token Management: Generates and refreshes JWT tokens automatically
  • FHIR STU3 Compliance: Full compliance with NHS Digital GP Connect specifications
  • Dual Server Modes: FastAPI web server and MCP server for LLM integration
  • Azure Ready: One-command deployment to Azure Container Apps
  • Session Management: Fixed HTTP session handling for reliable API calls

Authentication & Security

  • Automatic JWT Generation: RSA-signed JWT tokens with proper GP Connect claims
  • Token Lifecycle Management: Automatic token refresh and validation
  • Configurable Security: Support for custom RSA keys and organization settings
  • NHS Digital Compliance: Proper ASID, ODS codes, and interaction IDs
  • HTTPS Only: Production-ready security configuration

API Capabilities

  • Patient Management: Search, read, and manage patient records
  • Practitioner Management: Search and retrieve practitioner information
  • Organization Management: Access organization details and configurations
  • Appointment Management: Search slots, book appointments, and manage schedules āœ… WORKING
  • Real-time Integration: Live data access with GP Connect demonstrator

LLM Agent Integration

  • MCP Server Support: Native MCP protocol implementation for LLM agents
  • Tool-based Interface: Structured tools for each GP Connect operation
  • Async Operations: High-performance async/await implementation
  • Error Handling: Comprehensive error handling with detailed feedback
  • Public API Access: Direct HTTPS endpoints for LLM agent integration

šŸ“‹ Requirements

  • Python 3.8+
  • FastAPI
  • httpx
  • PyJWT with cryptography support
  • MCP (Model Context Protocol)
  • Pydantic v2

šŸ› ļø Installation

  1. Clone or create the project:
mkdir gp_connect_mcp_server
cd gp_connect_mcp_server
  1. Install dependencies:
pip install -r requirements.txt
  1. Configure environment:
cp .env.example .env
# Edit .env with your configuration

āš™ļø Configuration

Environment Variables

The server uses environment variables with the GP_CONNECT_ prefix:

# GP Connect API Configuration
GP_CONNECT_BASE_URL=https://orange.testlab.nhs.uk/gpconnect-demonstrator/v1/fhir
GP_CONNECT_ORGANIZATION_NAME=Dr Legg's Surgery
GP_CONNECT_ORGANIZATION_ODS_CODE=A20047
GP_CONNECT_PROVIDER_ASID=918999198993

# JWT Configuration
GP_CONNECT_JWT_EXPIRES_MINUTES=5
GP_CONNECT_PRACTITIONER_NAME=Dr. GP Connect
GP_CONNECT_PRACTITIONER_SDS_ID=G13579935

# Server Configuration
GP_CONNECT_HOST=0.0.0.0
GP_CONNECT_PORT=8000
GP_CONNECT_DEBUG=false

JWT Token Management

The server automatically generates and manages JWT tokens:

  • Automatic Generation: Tokens are generated on-demand with proper GP Connect claims
  • Automatic Refresh: Tokens are refreshed before expiry
  • Scope Management: Separate read and write tokens for different operations
  • RSA Signing: Uses RSA-512 algorithm with auto-generated or provided keys

šŸš€ Usage

FastAPI Web Server

Start the web server for REST API access:

python main.py fastapi

Or with custom settings:

python main.py fastapi --host 0.0.0.0 --port 8080 --debug

API Documentation: Available at http://localhost:8000/docs

MCP Server for LLM Agents

Start the MCP server for LLM integration:

python main.py mcp

The MCP server provides structured tools that LLM agents can use to interact with GP Connect APIs.

šŸ“š API Endpoints

Authentication

  • GET /token/info - Get current token information
  • POST /token/generate - Generate new JWT token

Foundations API

  • GET /fhir/metadata - Get capability statement
  • GET /fhir/Patient - Search patients
  • GET /fhir/Patient/{id} - Get specific patient
  • GET /fhir/Practitioner - Search practitioners
  • GET /fhir/Practitioner/{id} - Get specific practitioner
  • GET /fhir/Organization/{id} - Get organization details

Appointment Management

  • GET /fhir/Slot - Search available slots
  • GET /fhir/Appointment/{id} - Get appointment details
  • POST /fhir/Appointment - Book new appointment
  • GET /fhir/Patient/{id}/Appointment - Get patient appointments

MCP Integration

  • GET /mcp/tools - List available MCP tools
  • POST /mcp/tools/call - Call MCP tool

šŸ¤– MCP Tools for LLM Agents

The MCP server provides these tools for LLM agents:

Foundations Tools

  • gp_connect_capability_statement - Get API capabilities
  • gp_connect_search_patients - Search for patients
  • gp_connect_get_patient - Get patient details
  • gp_connect_search_practitioners - Search practitioners
  • gp_connect_get_practitioner - Get practitioner details
  • gp_connect_get_organization - Get organization details

Appointment Tools

  • gp_connect_search_slots - Find available appointment slots
  • gp_connect_get_appointment - Get appointment details
  • gp_connect_book_appointment - Book new appointment
  • gp_connect_get_patient_appointments - Get patient's appointments

Utility Tools

  • gp_connect_token_info - Get JWT token information

šŸ’” Example Usage

Python Client Example

import httpx
import asyncio

async def search_patients():
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "http://localhost:8000/fhir/Patient",
            params={"family": "Wright"}
        )
        return response.json()

# Run the example
result = asyncio.run(search_patients())
print(result)

MCP Tool Call Example

import httpx
import asyncio

async def call_mcp_tool():
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "http://localhost:8000/mcp/tools/call",
            json={
                "name": "gp_connect_search_patients",
                "arguments": {"family": "Wright"}
            }
        )
        return response.json()

result = asyncio.run(call_mcp_tool())
print(result)

Appointment Booking Example

import httpx
import asyncio

async def book_appointment():
    async with httpx.AsyncClient() as client:
        # First, search for available slots
        slots_response = await client.get(
            "http://localhost:8000/fhir/Slot",
            params={
                "start": "ge2024-01-01",
                "end": "le2024-01-31",
                "status": "free"
            }
        )
        slots = slots_response.json()
        
        if slots.get("entry"):
            slot_id = slots["entry"][0]["resource"]["id"]
            
            # Book the appointment
            booking_response = await client.post(
                "http://localhost:8000/fhir/Appointment",
                json={
                    "slot_id": slot_id,
                    "patient_id": "1",
                    "description": "GP consultation"
                }
            )
            return booking_response.json()

result = asyncio.run(book_appointment())
print(result)

šŸ”§ Development

Project Structure

gp_connect_mcp_server/
ā”œā”€ā”€ app/
│   ā”œā”€ā”€ fastapi_app.py      # FastAPI application
│   └── mcp_server.py       # MCP server implementation
ā”œā”€ā”€ config/
│   └── settings.py         # Configuration management
ā”œā”€ā”€ models/
│   └── gp_connect.py       # Pydantic models
ā”œā”€ā”€ services/
│   └── gp_connect_client.py # GP Connect API client
ā”œā”€ā”€ utils/
│   └── jwt_manager.py      # JWT token management
ā”œā”€ā”€ tests/                  # Test files
ā”œā”€ā”€ main.py                 # Main entry point
ā”œā”€ā”€ requirements.txt        # Dependencies
ā”œā”€ā”€ .env.example           # Environment configuration
└── README.md              # This file

Running Tests

pytest tests/ -v

Code Quality

# Format code
black .

# Sort imports
isort .

# Lint code
flake8 .

šŸ„ GP Connect Integration

Supported Operations

Foundations API
  • āœ… Capability Statement: Server metadata and capabilities
  • āœ… Patient Search: Find patients by name, NHS number, etc.
  • āœ… Patient Read: Get detailed patient information
  • āœ… Practitioner Search: Find healthcare practitioners
  • āœ… Practitioner Read: Get practitioner details
  • āœ… Organization Read: Get organization information
Appointment Management API
  • āœ… Slot Search: Find available appointment slots
  • āœ… Appointment Read: Get appointment details
  • āœ… Appointment Create: Book new appointments
  • āš ļø Patient Appointments: Limited support (demonstrator constraint)

FHIR Compliance

  • FHIR STU3: Full compliance with FHIR STU3 specification
  • GP Connect Profiles: Uses proper GP Connect FHIR profiles
  • Interaction IDs: Correct NHS Digital interaction identifiers
  • Resource Validation: Proper FHIR resource structure and validation

Authentication

  • JWT Tokens: RS512-signed JWT tokens with GP Connect claims
  • Automatic Management: Tokens generated and refreshed automatically
  • Proper Claims: Includes requesting device, organization, and practitioner
  • Scope Management: Separate read and write scopes

🌐 Production Deployment

Prerequisites

  1. NHS Digital Registration: Register for GP Connect access
  2. Technical Conformance: Complete NHS Digital conformance testing
  3. Certificates: Obtain production TLS certificates and ASIDs
  4. Private Keys: Generate and secure RSA private keys for JWT signing

Configuration

  1. Update Environment Variables:
GP_CONNECT_BASE_URL=https://your-production-gp-connect-endpoint
GP_CONNECT_ORGANIZATION_ODS_CODE=your-ods-code
GP_CONNECT_PROVIDER_ASID=your-asid
GP_CONNECT_JWT_PRIVATE_KEY=your-private-key
  1. Security Considerations:
  • Use proper SSL/TLS certificates
  • Secure private key storage
  • Enable proper CORS settings
  • Implement rate limiting
  • Add authentication for API access
  1. Deployment Options:
  • Docker containerization
  • Kubernetes deployment
  • Cloud platform deployment (AWS, Azure, GCP)
  • On-premises deployment

šŸ¤ Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Run quality checks
  6. Submit a pull request

šŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

šŸ†˜ Support

For support and questions:

  1. Check the documentation
  2. Review the API examples
  3. Check the test files for usage patterns
  4. Refer to NHS Digital GP Connect documentation

šŸ”— Related Resources


Note: This implementation is designed for integration with the GP Connect demonstrator and production GP Connect systems. Ensure proper NHS Digital registration and compliance before production use.

šŸš€ Quick Azure Deployment

One-Command Deployment

# Login to Azure
az login

# Deploy to Azure Container Apps
./deploy-to-azure.sh

# Get your public URL for LLM agents
# Output: https://your-app.azurecontainerapps.io

What Gets Deployed

  • āœ… Azure Container Registry: Secure container storage
  • āœ… Azure Container Apps: Serverless hosting with auto-scaling
  • āœ… HTTPS Endpoints: Public API access for LLM agents
  • āœ… Health Monitoring: Built-in health checks and logging
  • āœ… UK Data Residency: NHS-compliant hosting in Azure UK South

Cost Estimate

  • Development: ~Ā£35/month
  • Production: ~Ā£75/month
  • Pay-per-use: Scales with actual LLM agent usage

šŸŽÆ LLM Agent Integration

Public API Endpoints

Once deployed, your LLM agents can access:

Base URL: https://your-app.azurecontainerapps.io

Key Endpoints:
- GET  /health                    # Health monitoring
- GET  /mcp/tools/list           # Available MCP tools
- POST /mcp/tools/call           # Execute GP Connect operations
- GET  /docs                     # Interactive API documentation

Example LLM Agent Configuration

{
  "name": "GP Connect MCP Server",
  "base_url": "https://your-app.azurecontainerapps.io",
  "mcp_endpoint": "/mcp/tools/call",
  "authentication": "none",
  "tools": [
    "gp_connect_search_patients",
    "gp_connect_book_appointment",
    "gp_connect_search_slots"
  ]
}

āœ… Working Features (Tested & Validated)

Patient Management āœ…

  • Search patients by NHS number: 9658219004 → Cassie BRAY
  • Get patient details with full demographics
  • Support for multiple test patients

Appointment Booking āœ… FIXED & WORKING

  • Issue Resolved: "Both start and end date are required" error fixed
  • Successful Bookings: Multiple appointments booked successfully
  • Example: Cassie BRAY appointments (IDs: 12, 13) booked and confirmed

Slot Discovery āœ…

  • Find available appointment slots (787+ slots available)
  • Date range filtering (14-day GP Connect limit)
  • Status filtering (free, busy, etc.)

Organization Context āœ…

  • Dr Legg's Surgery (ODS: A20047)
  • Provider ASID: 918999198993
  • GP Connect v1.2 demonstrator integration

šŸ”§ Recent Fixes & Improvements

Session Management Fix āœ…

  • Fixed HTTP client session handling
  • Persistent connections for MCP tool calls
  • Improved reliability and performance

Appointment Booking Fix āœ…

  • Added required start and end date parameters
  • Added created timestamp field
  • Added booking organization extension
  • Fixed practitioner ID mapping (slot requires practitioner "1")

Error Handling āœ…

  • Proper HTTP status code mapping
  • Detailed error messages
  • Graceful failure handling

šŸ“¦ Deployment Files

Azure Deployment

  • deploy-to-azure.sh - Automated deployment script
  • Dockerfile.production - Production-optimized container
  • .github/workflows/deploy.yml - CI/CD pipeline
  • azure_deployment_guide.md - Complete deployment documentation

Configuration

  • .env.example - Environment configuration template
  • requirements.txt - Python dependencies
  • .gitignore - Git ignore patterns
  • docker-compose.yml - Local development setup