No description
  • Python 77.4%
  • JavaScript 15.5%
  • CSS 4.6%
  • HTML 2.3%
  • Dockerfile 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
carson c1dcd3b283 Fix explainer sanitiser swallowing full-document lessons (blank frames)
Void <meta>/<link>/<base>/<embed>/<frame> tags in DROP_WITH_CONTENT
incremented drop_depth but have no end tag, so everything after the
first <meta> was dropped. LLM explainers are full HTML documents
starting with <meta charset>, so the saved payload was just
'<html><head>' and the iframe rendered blank (Power Blocks, 2026-11-20).
Void drop tags now drop just themselves. Adds a regression test.
2026-11-20 15:40:29 -05:00
static Add OAuth 2.0 with Dynamic Client Registration for MCP 2026-11-20 15:17:06 -05:00
templates init 2026-11-20 14:47:26 -05:00
tests Fix explainer sanitiser swallowing full-document lessons (blank frames) 2026-11-20 15:40:29 -05:00
.dockerignore init 2026-11-20 14:47:26 -05:00
.env.example Fix OAuth discovery returning http:// behind a proxy 2026-11-20 15:24:16 -05:00
app.py Fix OAuth discovery returning http:// behind a proxy 2026-11-20 15:24:16 -05:00
core.py Fix explainer sanitiser swallowing full-document lessons (blank frames) 2026-11-20 15:40:29 -05:00
docker-compose.yml init 2026-11-20 14:47:26 -05:00
Dockerfile init 2026-11-20 14:47:26 -05:00
mcp_stdio.py init 2026-11-20 14:47:26 -05:00
README.md Fix OAuth discovery returning http:// behind a proxy 2026-11-20 15:24:16 -05:00
requirements.txt init 2026-11-20 14:47:26 -05:00

StudyMCP v1 — Learn it. See it. Quiz it.

A Flask web app + MCP server that helps you study. Log in, build topic folders, upload PDFs (or just name a topic), mint a temporary session key, hand it to your AI agent, and get interactive explainers, quizzes and flashcards back in your folder. Duolingo-like theme: feather green #58CC02, chunky pill buttons, streak flame + XP bar.

Built from the approved design doc (study-mcp-design-doc.pdf, v0.1). Backend is Flask (locked per the user's decision), SQLite for v1.

Run it (Docker — the intended way)

cp .env.example .env        # set a real SECRET_KEY
docker compose up -d --build

Then open http://<host>:8098

  • First account: register on the login page, or use the seeded demo account [email protected] / demo1234 (Biology folder with a sample quiz, flashcards and explainer). Set SEED_DEMO=0 in .env to skip seeding.
  • Data lives in ./data (SQLite + uploads) — that volume is the whole state.

Run it without Docker

pip install -r requirements.txt
python app.py          # http://127.0.0.1:8098

The 30-second flow

  1. Log in, create a folder for a topic (nest as deep as you like — the UI warns past 5 levels). Drag folders onto each other or use Move to…; the server refuses moves into a folder's own subfolder.
  2. Upload PDFs / DOCX / PPTX / TXT / Markdown / PNG / JPG (25 MB cap). Text is extracted on upload; scanned PDFs honestly report “Scanned image — text could not be extracted.” Images have no OCR in v1.
  3. Open the folder → Connect agent → mint a key (study_sk_…, shown once, with a Copy button and countdown). Default 2h; 1h / 2h / until revoked (max 24h). One active key per folder — a new one revokes the old.
  4. Paste the key into your MCP client as a Bearer token and connect to POST http://<host>:8098/mcp. The agent sees only that folder.
  5. Ask for /explain, /quiz-me, /flashcards, /summarise or /test-my-weak-spots. Lessons appear live in the folder.

Connecting an MCP client (remote HTTP)

  • Endpoint: POST http://<host>:8098/mcp
  • Auth: header Authorization: Bearer study_sk_...
  • Protocol: JSON-RPC 2.0, MCP 2025-06-18 — initialize, tools/list, tools/call, prompts/list, prompts/get, ping. Plain JSON replies, or SSE (Accept: text/event-stream) for streamable-HTTP clients.
  • Tools (10, all folder-scoped): study_browse, study_read_file, study_search, study_get_context, study_create_explainer, study_create_quiz, study_create_flashcards, study_create_summary, study_create_folder, study_record_progress. There is deliberately no delete tool — deleting is a human action in the web UI (Trash first, 30 days, Undo, Empty Trash asks twice).
  • Prompts: /explain, /quiz-me, /flashcards, /summarise, /test-my-weak-spots.

Example (curl):

KEY=study_sk_...
curl -X POST http://localhost:8098/mcp -H "Authorization: Bearer $KEY" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call",
       "params":{"name":"study_get_context","arguments":{}}}'

OAuth 2.0 (for clients that need it — e.g. the Gemini web app)

The Bearer session key above is enough for LM Studio and Gemini CLI, which accept a custom Authorization header. The Gemini web app (gemini.google.com) does not: its Custom apps connect over OAuth, not a Bearer API key. StudyMCP therefore also runs a small OAuth 2.0 authorization server (stdlib only — no new dependencies), and /mcp accepts both study_sk_... keys and OAuth access tokens (oauth_...), through the same folder-scoped checks. Nothing else about the 10 tools / 5 prompts changes.

Endpoints (base URL = where StudyMCP is served, e.g. https://study.example.com):

  • GET /.well-known/oauth-protected-resource/mcp — protected-resource metadata
  • GET /.well-known/oauth-authorization-server — issuer, authorize/token/ register/revoke endpoints, code + authorization_code/refresh_token, PKCE S256 only, client auth none / client_secret_post / client_secret_basic
  • POST /oauth/register — Dynamic Client Registration (RFC 7591). Send redirect_uris, client_name, token_endpoint_auth_method. Returns client_id (+ client_secret once, for confidential clients). Redirect URIs must be https, except http://localhost / http://127.0.0.1 loopback. Unauthenticated /mcp calls return HTTP 401 with a WWW-Authenticate header pointing at the protected-resource metadata.
  • GET /oauth/authorize — authorization code flow with PKCE S256 required (no PKCE = rejected). If you are not logged in, it sends you to the web login and back. The consent page (Duolingo theme) shows what the app gets — read + create in one folder, no delete, no other folders — and a folder picker (pre-selected if the scope names one, e.g. scope=read create folder:12). Approve → 10-minute single-use code. Deny → redirect with error=access_denied.
  • POST /oauth/token — grant_type=authorization_code (code + PKCE verifier
    • redirect URI + client auth) or grant_type=refresh_token. Returns access_token (oauth_..., 2h), refresh_token (7 days, single-use rotation: each refresh issues a new pair and revokes the old one), token_type: Bearer, expires_in: 7200, scope.
  • POST /oauth/revoke — revoke one access or refresh token (RFC 7009).
  • GET /api/oauth/authorizations / DELETE /api/oauth/authorizations/<id> — list / revoke connected apps in the web UI (Sessions panel → “Connected apps (OAuth)”). Revoking an authorization kills all its tokens at once.

Security: raw tokens, secrets and codes are stored only as SHA256 hashes and never logged; the client secret is shown once at registration. Redirect URIs must match exactly, authorization codes are single-use and bound to client + redirect URI + PKCE challenge, and OAuth tokens are folder-scoped with the same rate limits (120 calls/hour) and activity-feed logging as session keys.

Gemini web app, end to end

  1. Expose StudyMCP over public HTTPS — e.g. the Cloudflare tunnel (https://<your-host>/mcp). Gemini runs in Google's cloud and cannot reach localhost / plain http. Important (bug fixed 2026-11-20): behind a tunnel/reverse proxy the app must know its public URL, or OAuth discovery returns http:// URLs and Gemini rejects it. The app trusts X-Forwarded-Proto / X-Forwarded-Host (ProxyFix), and you can also force it in .env: PUBLIC_URL=https://studymcp.carsonmayn.com. Check it with curl https://<your-host>/.well-known/oauth-authorization-server — every URL in there must start with https://.
  2. In the Gemini web app: Settings → Connected Apps → Custom apps → Add a custom app, paste https://<your-host>/mcp, click Next.
  3. Gemini registers itself (DCR), then follows the OAuth sign-in: log in to StudyMCP, pick one folder on the consent page, approve.
  4. Gemini can now call the StudyMCP tools in that folder only. Revoke any time from StudyMCP → that folder → Connected apps (OAuth), or by deleting the custom app in Gemini.

Gemini CLI and LM Studio do not need any of this — keep using the Bearer session key there (see above).

Local stdio instead (official MCP SDK)

STUDY_SESSION_KEY=study_sk_... python mcp_stdio.py

Same tools, same folder scoping, over stdio. Uses the official mcp Python SDK (FastMCP on 1.x, MCPServer on 2.x — both supported).

Safety, by construction

  • Session keys are stored only as SHA256 hashes, checked (valid? not expired? not revoked? right folder?) on every MCP call. Scopes: read + create only. Rate limit 120 calls/hour/key, 50 agent-created lessons per session.
  • Explainer HTML is sanitised (allow-listed tags/attributes, no network or storage APIs — fetch, localStorage, WebSocket, eval, Function( etc. are rejected with a fixable reason) and rendered in a sandboxed iframe (sandbox="allow-scripts", no same-origin).
  • Quizzes/flashcards/summaries are structured JSON, rendered natively and scored in the web app. Lessons cite sources (From: lecture-3.pdf, p. 4) when files exist, otherwise are labelled “General knowledge — check against your course.”
  • Every agent action is logged in plain English in the folder's activity feed (“Agent read lecture-3.pdf”, “Agent created Practice Quiz 2”).

Tests

pip install -r requirements.txt
python -m pytest tests/ -q

18 tests (9 original + 9 OAuth in tests/test_oauth.py), covering: the original 9 — move-into-own-subfolder refused, expired/revoked key fails every MCP tool, key for Folder A refused on Folder B, explainer with fetch() rejected (and iframe stripped from clean HTML), delete → Trash → restore, quiz scoring + progress read-back, tools/prompts listing (10 tools, no delete tool), and text extraction on upload — plus OAuth: discovery + unauthenticated /mcp → 401 with WWW-Authenticate, DCR → PKCE authorize → token → /mcp tools/call with an OAuth token (and wrong-folder refused), PKCE enforced (wrong verifier / missing challenge rejected), refresh-token rotation (old refresh rejected, old access revoked), expired/revoked OAuth token fails, authorizations list + revoke, study_sk_... Bearer still works, confidential client via client_secret_basic (wrong secret → 401), and DCR rejecting a non-loopback http redirect URI.

What is NOT verified

  • Docker build is NOT verified. The sandbox cannot run containers (runc fails, no bridge network), so docker compose up --build has never been run here. The Dockerfile is standard python:3.12-slim + pip install
    • python app.py; please run it on a real host and report back.
  • No real MCP client end-to-end test. The /mcp endpoint was exercised with direct JSON-RPC calls (curl + pytest) and the stdio server with the official SDK's own protocol exchange — but not against Claude Desktop, Cursor, or any other live MCP client. The first real-client connection is the thing most likely to surface a quirk.
  • No real Gemini web-app end-to-end test. The OAuth flow was exercised end to end on a live local server (DCR → login redirect → consent page → code → token → /mcp tools/call → refresh rotation → revoke), but never against gemini.google.com — the sandbox cannot reach Google's cloud, and Gemini needs a public HTTPS URL. The first real Gemini connection may surface a quirk (e.g. the exact redirect URI / client auth method Gemini registers with).
  • No real PDF with scanned pages tested beyond the code path (pypdf returns near-empty text → failed status with the honest message).
  • No OCR for images in v1; no virus scanning of uploads (allow-list + size cap only).

Limits / known gaps (v1)

  • SQLite, not Postgres (single-container simplicity — see design doc p.8). Fine for one user / a household; not for concurrent heavy use.
  • Registration is open by default (ALLOW_REGISTRATION=true); set it to false after creating your account, and put the container behind a reverse proxy with HTTPS for anything beyond localhost.
  • Single active key per folder; no per-key delete (by design); no spaced repetition yet (Phase 2 in the design doc).
  • Explainer scripts may use DOM APIs but not network/storage; innerHTML is allowed inside the sandboxed iframe.

Layout

app.py            Flask app: web API + /mcp endpoint + SPA serving + OAuth 2.0
                  (discovery, DCR, authorize/consent, token, revoke)
core.py           DB, folders, files, keys, artifacts, sanitiser, MCP tools,
                  OAuth clients/codes/tokens/authorizations (hash-only)
mcp_stdio.py      Optional stdio MCP server (official MCP SDK)
static/           style.css, app.js (vanilla JS, no build step; Sessions panel
                  now also lists/revokes OAuth authorizations)
templates/        index.html
tests/            pytest suite (18 tests: test_studymcp.py + test_oauth.py)
Dockerfile  docker-compose.yml  .env.example  requirements.txt
data/             created at runtime: studymcp.db + uploads/ (volume)