chatgpt-mcp-data-platform
README.md
# Multi-Tenant Structured Data Platform with Remote MCP for ChatGPT
A production-minded, multi-tenant structured data platform that enables authenticated organization members to submit, query, and manage validated records through ChatGPT using a remote Model Context Protocol (MCP) server over Streamable HTTP, accompanied by a protected Next.js 15 admin dashboard.
---
## Key Architecture & Security Invariants
- **Zero-Trust Identity & Authorization**: No request can read or mutate organization data unless the server independently verifies identity from cryptographically validated bearer tokens (OIDC/OAuth 2.0), checks organization membership status, role, and operation permissions. Caller-supplied identity claims, roles, or tenant IDs in tool arguments are strictly ignored.
- **Admin Approval Workflow**: Users authenticate and request access to an organization (`request_access`). Organization owners or admins review, approve, reject, suspend, or revoke memberships. Only approved, active members can execute data operations. Revocation immediately cuts off access.
- **Strict Tenant Isolation**: Every database query scopes to `organization_id`. PostgreSQL Row-Level Security (RLS) is applied as defense-in-depth, backed by service-layer isolation.
- **Schema Validation & Guardrails**: Records are strictly validated against registered JSON Schemas before persistence. Unsupported JSON Schema keywords are rejected. Payload size, nesting depth, batch sizes, and filter operators are bounded to prevent abuse and denial of service.
- **Audited Mutations**: All approvals, rejections, suspensions, revocations, record creations, updates, and deletions are recorded in an append-only audit log with actor ID, organization ID, action, target, and safe metadata (never logging sensitive payloads or credentials).
- **Dual Interface**:
- **Remote MCP Server (Streamable HTTP)** for ChatGPT integration.
- **Protected REST API & Next.js Admin Dashboard** for tenant management, membership approvals, schema authoring, and audit inspection.
---
## Technology Stack
- **Backend**: Python 3.12, FastAPI, official Model Context Protocol (`mcp`) SDK, Starlette
- **Database & ORM**: PostgreSQL (production) / SQLite (`aiosqlite` for local dev), SQLAlchemy 2.0 (async), Alembic
- **Validation**: Pydantic v2, `jsonschema` (Draft 7/2020-12 restricted dialect)
- **Frontend**: Next.js 15 (App Router), TypeScript, Tailwind CSS, Heroicons
- **Auth & Security**: OAuth 2.0 / OIDC Bearer Tokens (PyJWT + cryptography), scoped permissions, zero-trust context resolution
- **Quality**: `pytest`, `pytest-asyncio`, `pytest-cov`, `httpx`, `ruff`, `mypy`, ESLint
---
## Repository Structure
```
.
├── backend/
│ └── app/
│ ├── main.py # FastAPI app & MCP Streamable HTTP mount
│ ├── config.py # Pydantic Settings v2 with safety validators
│ ├── logging_config.py # Structured JSON logger & payload redaction
│ ├── auth/ # Bearer validation, JWT/OIDC, Principals
│ │ ├── dependencies.py # FastAPI auth dependencies
│ │ ├── token_validation.py # OIDC JWKS & JWT verification
│ │ └── principal.py # AuthenticatedPrincipal & UserContext
│ ├── mcp/ # Remote MCP Server & Tool handlers
│ │ ├── server.py # FastMCP instance & ASGI lifespan
│ │ └── tools/ # access, records, admin tools
│ ├── api/ # REST API endpoints
│ │ ├── health.py # Liveness & readiness probes
│ │ ├── memberships.py # Membership requests & user org resolution
│ │ ├── records.py # Schema-validated CRUD & search
│ │ └── admin.py # Admin membership approvals & audits
│ ├── services/ # Business logic layer
│ │ ├── membership_service.py # State transitions & lifecycle
│ │ ├── authorization_service.py# RBAC & permission checking
│ │ ├── schema_service.py # JSON schema registration & validation
│ │ ├── record_service.py # Atomic validation & tenant-scoped queries
│ │ └── audit_service.py # Append-only audit trail logging
│ ├── db/ # Database persistence
│ │ ├── session.py # Async engine & sessionmaker
│ │ └── models.py # SQLAlchemy 2.x declarative models
│ ├── schemas/ # Pydantic models for API & MCP contracts
│ └── errors/ # Structured domain exceptions & HTTP mappings
├── frontend/ # Next.js 15+ TypeScript Admin Dashboard
│ ├── src/
│ │ ├── app/ # App Router pages (overview, members, records, schemas, audit, settings)
│ │ ├── components/ # Navbar, StatusBadge, ConfirmationModal
│ │ └── types/ # TypeScript definitions
│ └── patch-node26.js # Node.js 26 Windows filesystem patch
├── tests/
│ ├── unit/ # State transitions, permissions, schema validation
│ ├── integration/ # Full vertical slice flows
│ ├── security/ # Cross-tenant isolation, negative security tests
│ └── mcp/ # Tool discovery, argument validation, execution
├── docs/
│ ├── architecture.md # Component & request flow architecture
│ ├── security.md # Threat model, isolation & defense-in-depth
│ ├── oauth-chatgpt-setup.md # ChatGPT remote MCP OAuth configuration
│ └── deployment.md # Deployment guide & operational checklists
├── compose.yaml # Docker Compose local development stack
├── Dockerfile # Production multi-stage container
├── alembic.ini # Alembic database migration config
├── pyproject.toml # Python 3.12 dependencies
└── seed_demo.py # Standalone demo data seeder & token generator
```
---
## Quickstart & Local Development
### Prerequisites
- Python 3.12+ (or `uv`)
- Node.js 20+ and npm
- Git
### 1. Backend Setup
```bash
# Clone the repository
git clone https://github.com/adityakhadsecode/chatgpt-mcp-data-platform.git
cd chatgpt-mcp-data-platform
# Create virtual environment and install dependencies
uv venv --python 3.12
.venv\Scripts\activate # On Windows (or source .venv/bin/activate on Linux/macOS)
uv pip install -e ".[dev]"
# Copy environment variables
cp .env.example .env
```
### 2. Initialize & Seed Demo Data
Run the demo seeder to initialize the database with **Acme Corporation**, an **Owner / Admin** user, a sample `contact` schema, and pre-signed test JWT tokens:
```bash
python seed_demo.py
```
The script prints ready-to-use JWT tokens for:
- **Alice Admin**: Owner of Acme Corporation (full admin permissions).
- **Bob Newbie**: Unapproved user (for testing the approval workflow).
### 3. Run Backend & MCP Server
```bash
uvicorn backend.app.main:app --host 127.0.0.1 --port 8000 --reload
```
- **Liveness Probe**: [http://127.0.0.1:8000/health/live](http://127.0.0.1:8000/health/live)
- **Readiness Probe**: [http://127.0.0.1:8000/health/ready](http://127.0.0.1:8000/health/ready)
- **Interactive Swagger Docs**: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
- **Remote MCP Endpoint**: [http://127.0.0.1:8000/mcp](http://127.0.0.1:8000/mcp) (Streamable HTTP)
### 4. Run Admin Dashboard
In a new terminal:
```bash
cd frontend
npm install
npm run dev
```
Open [http://localhost:3000](http://localhost:3000) in your browser:
1. Navigate to `/settings`.
2. Paste the **Alice Admin Token** generated in step 2.
3. Manage members, register schemas, query records, and inspect audit logs.
---
## Remote MCP Tools Reference
The platform registers the following MCP tools over Streamable HTTP at `/mcp`:
| Tool Name | Permissions Required | Description |
| :--- | :--- | :--- |
| `get_my_access_profile` | Any Authenticated User | Inspect caller's organizations, roles, and membership status. |
| `request_membership` | Any Authenticated User | Submit a membership request to an organization. |
| `list_record_schemas` | Approved Member / Admin / Owner | List all active data schemas in the authorized organization. |
| `upload_records` | Approved Member / Admin / Owner | Ingest batch records after validating against declared JSON schema. |
| `query_records` | Approved Member / Admin / Owner | Query, filter, and paginate organization records. |
| `review_membership_request` | Org Admin / Owner | Approve, reject, suspend, or revoke a member. |
---
## Running Automated Tests
Run the full automated test suite (unit, integration, security, and MCP tests):
```bash
pytest -v
```
Run test suite with coverage:
```bash
pytest --cov=backend.app --cov-report=term-missing
```
Run code formatting and type checks:
```bash
ruff check .
ruff format --check .
mypy backend/app
```
---
## Production Deployment & Docker
Run the entire platform with containerized PostgreSQL:
```bash
docker compose up -d --build
```
For production configuration, OIDC provider setup (Auth0, Supabase, Okta, Keycloak), and ChatGPT integration, refer to the documentation:
- [Architecture Guide](docs/architecture.md)
- [Security Model & Threat Assessment](docs/security.md)
- [ChatGPT Remote MCP OAuth Integration Guide](docs/oauth-chatgpt-setup.md)
- [Deployment & Operations Guide](docs/deployment.md)
---
## License
MIT License. See [LICENSE](LICENSE) for details.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo issues