Skip to main content
Glama

LearnHub MCP Server

Let AI assistants talk to your LMS, safely.

A multi-tenant Model Context Protocol server that lets Claude, Cursor and any MCP client answer questions about users, trainings and enrollments in plain language: locally, or on AWS Lambda.

Tests   License: MIT

Python MCP AWS Lambda Amazon S3 OAuth 2.0 Pydantic FastAPI

πŸŽ“ Based on the architecture of a production MCP server I designed and deployed for a European EdTech platform. This is a clean-room re-implementation against a fictional API; it contains no proprietary code or data.

✨ Why LearnHub MCP?

"Which learners haven't started the Security Bootcamp?" "List our instructors in Engineering." The answers live behind a paginated, rate-limited, OAuth-protected REST API. Turning that API into AI tools takes more than wrapping endpoints:

  • 🏒 Each customer may only see their own data. One server, many tenants.

  • πŸ”‘ AI clients must never hold upstream credentials. They get an opaque client token, nothing more.

  • πŸ“š List endpoints return thousands of rows, which would blow up a model's context window.

  • 🚦 The API enforces rate limits. An eager AI agent can trip them in seconds.

LearnHub MCP handles all four, so the assistant only sees clean, safe, right-sized tools.

Related MCP server: mcp-gateway

πŸš€ Features

🏒 Multi-tenant by design

The tenant comes from a SHA-256-hashed client token, looked up server-side in a registry (JSON file or S3). It never comes from the model's input, so one tenant can't read another's records.

πŸ” OAuth handled for you

Per-tenant client-credentials tokens are cached, refreshed before they expire, and retried once with a fresh token if the API answers 401.

🧠 Context-window protection

Small results come back inline. Big ones are stored and summarized (count, fields, 5-row preview, result_id), and the model pages through them only if it needs to.

🚦 Rate-limit friendly

A per-tenant sliding-window limiter throttles requests before the API would answer 429. Transient failures are retried with exponential backoff and respect Retry-After.

πŸ”Œ One codebase, two transports

stdio for Claude Desktop and Cursor on your machine; HTTPS JSON-RPC on AWS Lambda for remote clients. Both share one ToolService.

βœ… Schemas that can't drift

Tool input schemas are generated from pydantic models, so what the model sees and what the server validates are always the same. Unknown fields are rejected.

βš™οΈ How it works

flowchart LR
    C["πŸ€– MCP client<br/>(Claude Desktop, Cursor)"] -- "stdio (local)<br/>or HTTPS + Bearer token (Lambda)" --> S["πŸŽ“ LearnHub MCP server"]
    S -- "SHA-256(client token)" --> R[("πŸ—‚οΈ Tenant registry<br/>JSON file or S3")]
    S -- "client_credentials" --> O["πŸ” OAuth endpoint"]
    S -- "Bearer access token" --> A["πŸ“š LMS REST API"]
    S -- "large results" --> F[("πŸ’Ύ Result store")]
  1. Tenant resolution. The caller's client token is hashed with SHA-256 and looked up in a tenant registry (a local JSON file or an S3 object, cached with a TTL). Plain-text tokens are never stored.

  2. OAuth. The server exchanges that tenant's client credentials for an access token, caches it per tenant, refreshes it before it expires, and retries once with a fresh token if the API answers 401.

  3. Rate-limited calls. A per-tenant sliding-window limiter throttles requests before the API would answer 429. Transient failures (429 with Retry-After, 5xx, network errors) are retried with exponential backoff.

  4. Pagination. List tools walk pages automatically up to the requested max_results.

  5. Context-window protection. Small results come back inline. Large ones are written to a result store, and the model gets a summary instead: count, field names, a 5-row preview and a result_id. It can then page through the full result with read_stored_result.

πŸ› οΈ Tools

Tool

What it does

πŸ‘₯ list_users

Users filtered by role, status, or name/email search

πŸ‘€ get_user

One user's profile

πŸ“š list_trainings

Trainings filtered by status or category

πŸ“˜ get_training

Training details with enrollment count and completion rate

🎯 list_training_participants

Enrolled learners with progress, completion and score

πŸ—‚οΈ list_stored_results

Large results saved during this session

πŸ“„ read_stored_result

Page through a stored result (offset, limit)

Errors go back to the model as tool errors (isError: true plus a readable message), so the assistant can correct itself. A failed tool call doesn't break the session.

🏁 Get started

Requires Python 3.11+ and uv.

git clone https://github.com/MedAmine-SUDO/learnhub-mcp-server.git
cd learnhub-mcp-server
uv sync --extra mock
cp .env.example .env

# Terminal 1: the mock LMS API on :8000
uv run learnhub-mock-api

# Terminal 2: replay the session shown above...
uv run python examples/demo_session.py

# ...or explore the server interactively
npx @modelcontextprotocol/inspector uv run learnhub-mcp

πŸ’‘ The demo registry (tenants.example.json) has two tenants: demo-token-acme (320 users) and demo-token-globex (140 users). All data is fictional.

{
  "mcpServers": {
    "learnhub": {
      "command": "uv",
      "args": ["--directory", "/path/to/learnhub-mcp-server", "run", "learnhub-mcp"],
      "env": { "LEARNHUB_CLIENT_TOKEN": "demo-token-acme" }
    }
  }
}

Then ask Claude: "Which learners haven't started the first Security training?"

☁️ Deploy to AWS Lambda

lambda_handler.py speaks MCP JSON-RPC over HTTPS: initialize, ping, tools/list and tools/call, plus notifications. The client token arrives as Authorization: Bearer <token> (or X-Client-Token). The service lives at module level, so warm invocations reuse cached OAuth tokens, the tenant registry and pooled connections.

./deploy/build_lambda.sh                       # -> build/lambda.zip (manylinux, Python 3.12)
sam deploy --template-file deploy/template.yaml --guided

Remote MCP clients then connect to the Function URL:

{ "mcpServers": { "learnhub": { "url": "https://<id>.lambda-url.<region>.on.aws/",
                                  "headers": { "Authorization": "Bearer <client-token>" } } } }

Floci is a free local AWS emulator. It runs Lambda functions as real containers and serves S3, so you can test the full remote path (S3 tenant registry, Lambda, OAuth, API) without an AWS account:

docker run -d --name floci -p 4566:4566 -v /var/run/docker.sock:/var/run/docker.sock floci/floci
MOCK_HOST=0.0.0.0 uv run learnhub-mock-api
./deploy/build_lambda.sh
uv run --extra s3 python deploy/deploy_floci.py

To point the stdio server at an S3 registry on Floci, set LEARNHUB_TENANT_REGISTRY=s3://learnhub-config/tenants.json and AWS_ENDPOINT_URL=http://localhost:4566.

πŸ”’ Security

🏒 Tenant isolation

The tenant is resolved from the client token on the server, never from tool arguments, and every upstream call uses that tenant's own OAuth token.

#️⃣ Hashed client tokens

The registry stores only SHA-256 hashes, compared in constant time. A leaked registry file holds no usable tokens.

πŸ”‘ No credentials for the AI

Clients hold an opaque token. Upstream client secrets stay on the server and can be rotated without touching any client.

πŸ›‘οΈ Validated inputs

Pydantic validates every tool call and rejects unknown fields. result_id values are pattern-checked, so they can't escape the result store directory.

πŸ™ˆ Safe errors

The model sees readable error types and messages. Unexpected exceptions are logged server-side and returned as a generic error.

πŸ§ͺ Tests

uv run pytest

The tests run the real mock API in-process through httpx.ASGITransport, so there's no network and nothing to start. They cover:

  • βœ… tools end to end

  • βœ… tenant isolation (one tenant can't read another's records)

  • βœ… token caching and refresh, and 401 re-authentication

  • βœ… 429 and 5xx retries, and the rate limiter (with an injected clock)

  • βœ… result storage, paging and path-traversal protection

  • βœ… the Lambda JSON-RPC transport

🧰 Tech stack

Layer

Technology

Protocol

Model Context Protocol Β· MCP Python SDK 2.x (stdio) Β· hand-rolled JSON-RPC handler (Lambda)

Core

Python 3.11+ Β· httpx (async) Β· pydantic 2

Auth

OAuth 2.0 client credentials Β· SHA-256 hashed client tokens

Cloud

AWS Lambda (Function URL) Β· Amazon S3 Β· AWS SAM

Local AWS

Floci

Mock LMS

FastAPI Β· uvicorn

Tooling

uv Β· pytest Β· GitHub Actions

β”œβ”€β”€ src/learnhub_mcp/
β”‚   β”œβ”€β”€ server.py          # MCP over stdio (local transport) + shared tool-error handling
β”‚   β”œβ”€β”€ lambda_handler.py  # MCP JSON-RPC over HTTPS (Lambda Function URL)
β”‚   β”œβ”€β”€ tools.py           # Tool specs (pydantic schemas) and handlers
β”‚   β”œβ”€β”€ api_client.py      # LMS client: auth injection, rate limiting, retries, pagination
β”‚   β”œβ”€β”€ auth.py            # OAuth client-credentials token manager
β”‚   β”œβ”€β”€ tenants.py         # Hashed-token tenant registry (file or S3)
β”‚   β”œβ”€β”€ rate_limit.py      # Sliding-window rate limiter
β”‚   β”œβ”€β”€ result_store.py    # Large-result storage for context-window protection
β”‚   └── runtime.py, config.py
β”œβ”€β”€ src/mock_api/          # FastAPI mock LMS: OAuth, tenants, pagination, rate limits, fake data
β”œβ”€β”€ deploy/                # Lambda build script, SAM template, Floci deploy script
β”œβ”€β”€ examples/              # demo_session.py: a scripted MCP client session
β”œβ”€β”€ tests/
└── .github/workflows/tests.yml
  • One service, two transports. ToolService holds all the logic; stdio and Lambda are thin adapters over it.

  • Errors go to the model as tool errors (isError: true plus a readable message), so the assistant can correct itself. A failed tool call doesn't break the session.

  • Lambda result storage uses /tmp, which lasts only as long as a warm container. A multi-instance production deployment would put the result store on S3 with a lifecycle rule.

  • Secrets: the demo registry holds client secrets inline for simplicity. In production, the registry should reference AWS Secrets Manager entries instead.

πŸ—ΊοΈ Roadmap

  • Result store on S3 with a lifecycle rule, shared across Lambda instances

  • Tenant registry entries that reference AWS Secrets Manager instead of inline secrets

  • Switch the Lambda transport to the SDK's streamable-HTTP transport

  • Per-tenant metrics (tool calls, latency, upstream errors) in CloudWatch

  • More tools: certificates, learning paths, completion reports

Made with β˜• by MedAmine-SUDO

If this helps you wire an API into your AI assistant, consider giving it a ⭐

Available Tools

7 tools
get_trainingC

Get one training's details by id.

Inputs: training_id (required).

get_userA

Get one user's full profile by id.

Inputs: user_id (required).

list_stored_resultsA

List large results saved earlier in this session.

Inputs: no named parameters.

list_training_participantsB

List the learners enrolled in a training with their progress and score, optionally filtered by completion status.

Inputs: training_id (required), completion, max_results.

list_trainingsC

List trainings (courses), optionally filtered by status or category.

Inputs: status, category, max_results.

list_usersB

List users of your organization, optionally filtered by role, status or a name/email search. Large result sets are stored and summarized.

Inputs: role, search, status, max_results.

read_stored_resultB

Read a page of a stored result by result_id, using offset and limit.

Inputs: result_id (required), limit, offset.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 7 tools

    Disambiguation5/5

    Each tool has a clearly distinct scope: users vs. trainings vs. participants vs. stored-result pagination. The list/get pairs target different granularity, and the stored-result tools are cleanly split between listing saved results and reading a page.

    Naming Consistency5/5

    All tool names follow a predictable snake_case verb_noun pattern (list_*, get_*, read_*). Minor verb variation between get and read is contextually appropriate and does not create confusion.

    Tool Count5/5

    Seven tools is well-scoped for an LMS read/inspection server. Each tool earns its place and there is no obvious bloat or thinness.

    Completeness3/5

    The surface covers read/list access for users, trainings, participants, and paginated stored results, but lacks any create, update, delete, or enrollment mutation operations. For a learning-management domain, this leaves notable lifecycle gaps.

    Maintenance

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI assistants to query business databases directly via natural language, with enforced read-only access and secure query limits. Supports SQLite and PostgreSQL, and works with any OpenAI-compatible model.
      0
      ISC
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables secure exposure of internal tools to LLM clients with API-key authentication, tenant isolation, per-tool guardrails, PII scrubbing, rate limiting, audit logging, and telemetry over stdio and HTTP/SSE.
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      Enables natural-language, read-only access to a user's own learning-management account for courses, assignments and deadlines, lecture attendance, notices, grades, and syllabus evidence, including reading page/slide/cell locations inside PDF, Office, HWP/HWPX, HTML, and ZIP attachments. Runs locally over stdio or remotely over OAuth-protected Streamable HTTP for desktop and mobile clients, and can compare changes against a locally encrypted baseline.
      19
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables students, instructors, and account administrators to manage courses, assignments, submissions, grades, discussions, modules, files, enrollments, users, and institutional reports through natural language. Supports both local stdio and streamable HTTP transports, with Docker and Kubernetes deployment for cloud-ready use.
      21 npm
      MIT