Skip to main content
Glama
Canvas MCP

Canvas MCP

by Drastixs
README.md
# Canvas MCP on Cloudflare Workers (stateless)

A [Model Context Protocol](https://modelcontextprotocol.io/) server for Canvas LMS that runs on Cloudflare Workers.

The server is **stateless**:

- It issues no MCP session (no `Mcp-Session-Id`). Each HTTP request is complete on its own.
- It stores nothing: no Durable Objects, KV, D1, R2 or files.
- The **client keeps all Canvas credentials** and sends them in HTTP headers on every request. The Worker uses them for that one request and then discards them.

Live endpoint: **`https://canvas-mcp.accelerateme.workers.dev/mcp`**
(Health check: `https://canvas-mcp.accelerateme.workers.dev/health`)

This repo is a fork of [Drastixs/mcp-canvas-lms](https://github.com/Drastixs/mcp-canvas-lms) (branch `home-lab-deploy`), which is a fork of [DMontgomery40/mcp-canvas-lms](https://github.com/DMontgomery40/mcp-canvas-lms) (MIT).

---

## Connect an agent

> **If you are an AI agent and the user asked you to connect yourself to Canvas, do steps 1 to 4 in sequence.**
> Do not print secret values in chat or logs. Do not write them into a git repository.

### Step 1: Get Canvas credentials

Use **one** of these credential types.

| Type | Headers to send | When to use |
| --- | --- | --- |
| **A. Refresh credentials (recommended)** | `X-Canvas-Refresh-Token`, `X-Canvas-Client-Id`, `X-Canvas-Client-Secret` | Your university uses SSO and you logged in with the Canvas mobile OAuth flow. The Worker gets a new access token on each request. |
| **B. Personal access token** | `Authorization: Bearer <token>` (or `X-Canvas-Token`) | Your Canvas lets users make tokens (Canvas → Account → Settings → *+ New Access Token*). This is the simplest option. |

Do **not** send a short-lived OAuth access token by itself. Canvas cancels the old access token each time a refresh occurs, so it stops working soon.

**To get type A credentials**, run this on the user's computer (it needs Node 18+, and Python 3 for the login):

```bash
git clone https://github.com/Drastixs/canvas-mcp-cloudflare && cd canvas-mcp-cloudflare
npm install

# Option 1: a new login only for this client (recommended).
# A Chromium window opens. The user logs in with SSO and approves MFA.
CANVAS_EMAIL='user@university.ac.uk' CANVAS_PASSWORD='...' npm run credentials -- --login --format env

# Option 2: use the tokens that already exist in ~/.canvas-mcp/tokens.json
npm run credentials -- --format env
```

The command prints `export CANVAS_DOMAIN=... CANVAS_REFRESH_TOKEN=... CANVAS_CLIENT_ID=... CANVAS_CLIENT_SECRET=...`.
Other formats: `--format json`, `--format claude` (a `claude mcp add` command), `--format codex` (a Codex config block).
`--domain <host>` sets the Canvas domain (default `canvas.manchester.ac.uk`).

Use a separate login (Option 1) for each server that refreshes tokens. If two servers share one refresh token, each refresh cancels the access token of the other server. The Worker retries in this case, but a separate login is better.

### Step 2: Keep the credentials in the client

Put the values in the user's shell profile or secret manager as environment variables, for example in `~/.config/canvas-mcp.env` with mode `600`:

```bash
export CANVAS_DOMAIN='canvas.manchester.ac.uk'
export CANVAS_REFRESH_TOKEN='...'
export CANVAS_CLIENT_ID='...'
export CANVAS_CLIENT_SECRET='...'
```

Then make the client config read the variables. Do not put the literal values in a config file that is in git.

### Step 3: Add the server to the client

**Claude Code** – add to `.mcp.json` (project) or use `claude mcp add` (user). `${VAR}` is read from the environment:

```json
{
  "mcpServers": {
    "canvas": {
      "type": "http",
      "url": "https://canvas-mcp.accelerateme.workers.dev/mcp",
      "headers": {
        "X-Canvas-Domain": "${CANVAS_DOMAIN}",
        "X-Canvas-Refresh-Token": "${CANVAS_REFRESH_TOKEN}",
        "X-Canvas-Client-Id": "${CANVAS_CLIENT_ID}",
        "X-Canvas-Client-Secret": "${CANVAS_CLIENT_SECRET}"
      }
    }
  }
}
```

or:

```bash
claude mcp add --transport http --scope user canvas https://canvas-mcp.accelerateme.workers.dev/mcp \
  --header "X-Canvas-Domain: $CANVAS_DOMAIN" \
  --header "X-Canvas-Refresh-Token: $CANVAS_REFRESH_TOKEN" \
  --header "X-Canvas-Client-Id: $CANVAS_CLIENT_ID" \
  --header "X-Canvas-Client-Secret: $CANVAS_CLIENT_SECRET"
```

(The second form writes the values into `~/.claude.json`.)

**Codex** – `~/.codex/config.toml`. `env_http_headers` maps a header to an environment variable name:

```toml
[mcp_servers.canvas]
url = "https://canvas-mcp.accelerateme.workers.dev/mcp"

[mcp_servers.canvas.env_http_headers]
"X-Canvas-Domain" = "CANVAS_DOMAIN"
"X-Canvas-Refresh-Token" = "CANVAS_REFRESH_TOKEN"
"X-Canvas-Client-Id" = "CANVAS_CLIENT_ID"
"X-Canvas-Client-Secret" = "CANVAS_CLIENT_SECRET"
```

**Cursor, Windsurf, VS Code and other clients with remote HTTP support** – use the same `url` and `headers` as the Claude Code JSON above, in that client's MCP config file.

**Clients with personal access token (type B)** – send only one header:

```json
"headers": { "Authorization": "Bearer ${CANVAS_API_TOKEN}" }
```

**Clients that support only stdio** (for example older Claude Desktop) – use the `mcp-remote` bridge:

```json
{
  "mcpServers": {
    "canvas": {
      "command": "npx",
      "args": [
        "-y", "mcp-remote", "https://canvas-mcp.accelerateme.workers.dev/mcp",
        "--transport", "http-only",
        "--header", "X-Canvas-Refresh-Token:${CANVAS_REFRESH_TOKEN}",
        "--header", "X-Canvas-Client-Id:${CANVAS_CLIENT_ID}",
        "--header", "X-Canvas-Client-Secret:${CANVAS_CLIENT_SECRET}"
      ],
      "env": {
        "CANVAS_REFRESH_TOKEN": "...",
        "CANVAS_CLIENT_ID": "...",
        "CANVAS_CLIENT_SECRET": "..."
      }
    }
  }
}
```

Claude.ai web "custom connectors" cannot send custom headers, so they cannot use this server.

### Step 4: Verify

1. Restart the client (or reload its MCP servers) so it reads the new config and environment.
2. Call the tool `canvas_check_auth`. The result must show `"authenticated": true`.
3. Call `canvas_list_courses`. The result must show a `count` greater than 0.

You can also check from a shell:

```bash
curl -s https://canvas-mcp.accelerateme.workers.dev/mcp \
  -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' \
  -H "X-Canvas-Refresh-Token: $CANVAS_REFRESH_TOKEN" \
  -H "X-Canvas-Client-Id: $CANVAS_CLIENT_ID" \
  -H "X-Canvas-Client-Secret: $CANVAS_CLIENT_SECRET" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"canvas_check_auth","arguments":{}}}'
```

### Troubleshooting

| Symptom | Cause | Fix |
| --- | --- | --- |
| Tool result `"code": "auth_required"` | The client sent no credentials. | Make sure the environment variables are set in the process that starts the client. Restart the client. |
| `canvas_check_auth` shows `"refresh_error": "refresh_token_rejected"` | The refresh token was revoked (for example, the "Pixel 7" token was deleted in Canvas). | Do Step 1 again with `--login`. |
| `Canvas API Error (401): Invalid access token` with type B | The personal access token expired or was deleted. | Make a new token in Canvas settings. |
| HTTP 403 `Canvas domain ... is not allowed` | `X-Canvas-Domain` is not in `ALLOWED_CANVAS_DOMAINS`. | Use an allowed domain, or deploy your own Worker (see below). |
| HTTP 401 `Missing or wrong X-MCP-Access-Key` | The Worker has `MCP_ACCESS_KEY` set. | Add the `X-MCP-Access-Key` header. |
| HTTP 405 on GET or DELETE | Normal. The server is stateless, so it has no event stream and no session to delete. | Clients must use POST. All current MCP SDK clients do this. |

---

## Notes for agents that use the tools

- Start with `canvas_list_courses` to get course IDs. Most other tools need `course_id`.
- List tools show the first 5 items plus `count` and `has_more`. Send `"include_raw": true` to get all items.
- `canvas_api` calls any Canvas REST endpoint (GET only on the public deployment). Use it for data that has no dedicated tool, for example `{"path": "courses/123/pages/week-1"}`.
- The default tool set is read-only (36 tools). Write tools are off.
- Each tool call is independent. Do not expect the server to remember anything between calls.

---

## Header reference

| Header | Required | Purpose |
| --- | --- | --- |
| `Authorization: Bearer <token>` or `X-Canvas-Token` | One of these, or the three refresh headers | Canvas access token (personal access token). |
| `X-Canvas-Refresh-Token`, `X-Canvas-Client-Id`, `X-Canvas-Client-Secret` | See above | OAuth refresh credentials. The Worker refreshes on each request and retries on a 401. |
| `X-Canvas-Domain` | No (default `CANVAS_DOMAIN`) | Canvas host, for example `canvas.manchester.ac.uk` or `school.instructure.com`. |
| `X-Canvas-Toolsets` | No | `student` (default), `instructor`, `admin`, or `all`, comma-separated. |
| `X-MCP-Access-Key` | Only if the Worker sets `MCP_ACCESS_KEY` | Shared key that limits who can use the Worker. |

## How it works

```
MCP client (keeps credentials)
   │  POST /mcp  + JSON-RPC body + X-Canvas-* headers
   ▼
Cloudflare Worker (src/worker.ts)
   │  1. Check the domain allowlist and optional access key
   │  2. Make a new CanvasClient, MCP Server and transport for this request only
   │  3. If needed, exchange the refresh token for an access token (not stored)
   ▼
Canvas REST API  ──►  JSON response to the client  ──►  everything is discarded
```

Code layout:

| File | Purpose |
| --- | --- |
| `src/server.ts` | Runtime-neutral core: tool definitions and MCP handlers (`CanvasMCPCore`). |
| `src/worker.ts` | Cloudflare Worker entry (stateless streamable HTTP, credentials from headers). |
| `src/index.ts` | Node entry: stdio, or a stateless streamable HTTP server. |
| `src/auth/provider.ts` | Auth provider interface and the request-credentials provider used by the Worker. |
| `src/auth/file-provider.ts` | Node-only provider (`~/.canvas-mcp/tokens.json`, mobile OAuth login). |
| `src/cli/client-credentials.ts` | `npm run credentials`: prints the values a client must keep. |

---

## Deploy your own Worker

```bash
npm install
npx wrangler login
# Edit "vars" in wrangler.jsonc: CANVAS_DOMAIN and ALLOWED_CANVAS_DOMAINS
npm run deploy
```

Configuration (`vars` in `wrangler.jsonc`):

| Variable | Default | Purpose |
| --- | --- | --- |
| `CANVAS_DOMAIN` | `canvas.manchester.ac.uk` | Domain used when the client sends no `X-Canvas-Domain`. |
| `ALLOWED_CANVAS_DOMAINS` | `canvas.manchester.ac.uk,*.instructure.com` | Domains clients may use. `*.x.com` matches subdomains. If empty, only `CANVAS_DOMAIN` is allowed. |
| `CANVAS_TOOLSETS` | `student` | Default toolsets. |
| `MCP_TOOL_ALLOWLIST` | empty | Exact tool names to expose. Empty means the read-only default set. |
| `CANVAS_API_ALLOW_WRITES` | `false` | `true` lets `canvas_api` send POST/PUT/DELETE. |
| `ALLOWED_ORIGINS` | empty | Browser origins allowed by CORS. Empty means any origin. |
| `MCP_ACCESS_KEY` (secret) | not set | Set with `npx wrangler secret put MCP_ACCESS_KEY`. Clients must then send `X-MCP-Access-Key`. |

Other commands: `npm run dev:worker` (local Worker on port 8787), `npm run tail` (live logs), `npm test`.

## Security notes

- Credentials go over HTTPS in headers. The Worker does not log header values or tokens. It logs only the Canvas API path of each call.
- The domain allowlist stops the Worker from being used to send requests to other hosts.
- Anyone who has your refresh credentials can read your Canvas. Keep them as you would keep a password. To revoke them, delete the "Pixel 7" integration in Canvas → Account → Settings → Approved Integrations.
- Write operations are off by default. Turn them on only for a private deployment that has `MCP_ACCESS_KEY` set.

## Run locally with Node (optional)

The original Node modes still work:

```bash
npm run build
CANVAS_DOMAIN=canvas.manchester.ac.uk node build/index.js        # stdio, uses ~/.canvas-mcp/tokens.json
MCP_TRANSPORT=streamable-http MCP_BEARER_TOKEN=change-me \
  CANVAS_DOMAIN=canvas.manchester.ac.uk node build/index.js       # stateless HTTP on 127.0.0.1:3000/mcp
```

The Node HTTP mode is also stateless now (no sessions). It keeps the Canvas token on the server and needs `MCP_BEARER_TOKEN`.

## License

MIT. See [LICENSE](LICENSE).