rbade1234/gp-connect-mcp-server
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.
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
- Clone or create the project:
mkdir gp_connect_mcp_server
cd gp_connect_mcp_server
- Install dependencies:
pip install -r requirements.txt
- 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 informationPOST /token/generate
- Generate new JWT token
Foundations API
GET /fhir/metadata
- Get capability statementGET /fhir/Patient
- Search patientsGET /fhir/Patient/{id}
- Get specific patientGET /fhir/Practitioner
- Search practitionersGET /fhir/Practitioner/{id}
- Get specific practitionerGET /fhir/Organization/{id}
- Get organization details
Appointment Management
GET /fhir/Slot
- Search available slotsGET /fhir/Appointment/{id}
- Get appointment detailsPOST /fhir/Appointment
- Book new appointmentGET /fhir/Patient/{id}/Appointment
- Get patient appointments
MCP Integration
GET /mcp/tools
- List available MCP toolsPOST /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 capabilitiesgp_connect_search_patients
- Search for patientsgp_connect_get_patient
- Get patient detailsgp_connect_search_practitioners
- Search practitionersgp_connect_get_practitioner
- Get practitioner detailsgp_connect_get_organization
- Get organization details
Appointment Tools
gp_connect_search_slots
- Find available appointment slotsgp_connect_get_appointment
- Get appointment detailsgp_connect_book_appointment
- Book new appointmentgp_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
- NHS Digital Registration: Register for GP Connect access
- Technical Conformance: Complete NHS Digital conformance testing
- Certificates: Obtain production TLS certificates and ASIDs
- Private Keys: Generate and secure RSA private keys for JWT signing
Configuration
- 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
- Security Considerations:
- Use proper SSL/TLS certificates
- Secure private key storage
- Enable proper CORS settings
- Implement rate limiting
- Add authentication for API access
- Deployment Options:
- Docker containerization
- Kubernetes deployment
- Cloud platform deployment (AWS, Azure, GCP)
- On-premises deployment
š¤ Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Run quality checks
- Submit a pull request
š License
This project is licensed under the MIT License - see the LICENSE file for details.
š Support
For support and questions:
- Check the documentation
- Review the API examples
- Check the test files for usage patterns
- Refer to NHS Digital GP Connect documentation
š Related Resources
- NHS Digital GP Connect
- GP Connect Developer Documentation
- FHIR STU3 Specification
- Model Context Protocol (MCP)
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
andend
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 scriptDockerfile.production
- Production-optimized container.github/workflows/deploy.yml
- CI/CD pipelineazure_deployment_guide.md
- Complete deployment documentation
Configuration
.env.example
- Environment configuration templaterequirements.txt
- Python dependencies.gitignore
- Git ignore patternsdocker-compose.yml
- Local development setup