Skip to main content
Glama
Notion MCP Portal

Notion MCP Portal

by rriordan
README.md
# notion-mcp-portal

A Notion API MCP server on Cloudflare Workers, protected by Cloudflare Access and served through a Cloudflare MCP server portal.

- **One URL** for every MCP client (`https://mcp.example.com/mcp`), with more servers addable behind it later.
- **People log in with SSO** through Access Managed OAuth, so Claude, ChatGPT and other hosted clients connect as an ordinary custom connector.
- **Headless agents use a service token** and never need a browser.
- **The Notion token never leaves the Worker.** Clients and models never see it.
- **Runs on the Workers Free plan.** No Durable Objects, no sandbox.

I built this for two reasons. First, so all my agents (Claude and ChatGPT on the web, plus a self-hosted agent on a home server) could share one authenticated Notion connection instead of each holding an integration token. Second, for a second rate-limit budget: Notion limits each connection separately, so bulk and scheduled jobs can run here without using up the official connector's budget. Everything here runs in production for me; this repo is the cleaned-up, reusable version.

## Why not just use Notion's official MCP connector?

The official hosted connector is easy to set up and does things this can't (see below). This project makes different trade-offs:

| | Official hosted Notion MCP | notion-mcp-portal |
|---|---|---|
| **What the AI can reach** | Everything your Notion account can see (OAuth as you) | Only the pages you share with the integration |
| **Headless agents** | Per-user OAuth in a browser | Service token: two headers, no browser |
| **Tool footprint in context** | 77 tools, 104,604 tokens of definitions in my connector (measured Nov 2026) | 2 tools, 1,746 tokens (2,074 with the optional `governance_bundle`) |
| **Plan gating** | Some tools and search filters need Business/Enterprise or a "full version" | The public REST API; workspace limits such as file-upload size still apply |
| **Model steering** | Upsells built in: its server instructions tell your assistant to suggest saving work in Notion and to link Notion's upgrade card when a tool needs a higher plan | No server instructions. Tool text only says how to call the API |
| **Rate limits** | Notion's API limits apply to every tool call: 180 requests/min per connection (600 on Business/Enterprise) plus a workspace-wide cap. Retries once if the wait is 2 s or less; otherwise returns `rate_limited`. Plans below Business with Notion AI also get a usage allowance for SQL queries | The same Notion API limits, on the integration's own budget, separate from the official connector's (both count toward the workspace cap). All your clients share that budget. Retries 429s up to twice, honoring `Retry-After` (capped at 10 s). The Workers Free plan adds a cap of 100,000 requests/day |
| **Who changes it** | Notion can change tools and instructions at any time | You pin dependency versions and decide when to deploy |
| **Audit trail** | Notion's | Cloudflare Access logs every connection, plus Worker logs |
| **Where the Notion credential lives** | An OAuth grant held by each client | One integration token, only inside the Worker; clients hold a revocable Cloudflare grant |

### Measured

Token counts from the Anthropic token-counting API (`claude-opus-5-5`), measured on my workspace with [`npm run bench`](bench/README.md). Tool definitions were measured on 2026-11-07 for the official connector (its `tools/list` as my account saw it) and on 2026-11-10 for this server (1.3.0, counting the definitions only; `governance_bundle` is listed only when `GOVERNANCE_README_ID` is set). The tool-result rows below were measured on 2026-10-30, before 1.2.0 fits long replies to the cap, so they are not comparable with a rerun today, except the `governance_bundle` row, measured on 2026-11-10 against the deployed 1.3.0. Your pages will differ.

| What the model reads | Tokens |
|---|---|
| Tool definitions: official connector (77 tools) | 104,604 |
| Tool definitions: notion-mcp-portal (2 tools) | 1,746 |
| Tool definitions: notion-mcp-portal with `governance_bundle` (3 tools) | 2,074 |

| Tool result | Raw Notion JSON | Compact (default) | Saved |
|---|---|---|---|
| Retrieve a page | 1,033 | 581 | 44% |
| Query a data source (10 rows) | 10,177 | 5,870 | 42% |
| Block children (one level) | 3,313 | 2,424 | 27% |
| Search (10 results) | over the 24,000-character cap, truncated | 8,491 | fits whole |
| Page as Markdown (whole page) | 4,038 | 4,007 | 1% |
| Session-start bundle (`governance_bundle`, no guides or schemas) | n/a | 6,280 | n/a |

Complete walks of real lists (1.2.0), measured on my workspace on 2026-11-06 with [`test/scan.mjs`](test/scan.mjs): one request per page at 3 s apart, every page followed by its `next_cursor`, each list walked twice.

| List (compact) | Rows | Pages | Lost cursors | Cut rows | Two walks agree |
|---|---|---|---|---|---|
| Tasks | 58 | 6 | 0 | 0 | yes |
| Findings | 72 | 12 | 0 | 0 | yes |
| Captures | 201 | 21 | 0 | 0 | yes |

The official connector's rows mode stopped at 100 of the 201 Captures rows with `has_more` set and no cursor to continue. Token sizes above are unchanged from 1.1.0.

**Use the official connector instead** if you need features the public API doesn't expose: Notion AI search across connected apps, meeting-note transcripts, Notion Calendar, Notion's memory and agent sessions. Also choose it if a team needs per-person Notion permissions, or if you just want zero setup.

## Architecture

```mermaid
flowchart LR
  C["Hosted client<br/>(Claude connector)"] -- "OAuth (Managed OAuth + DCR)" --> P
  A["Headless agent"] -- "CF-Access-Client-Id / Secret" --> P
  subgraph CF["Cloudflare"]
    P["MCP server portal<br/>mcp.example.com<br/>Access app: mcp_portal"] --> S["Access app: mcp<br/>notion.example.com"]
    S --> W["Worker notion-api-mcp<br/>verifies Cf-Access-Jwt-Assertion"]
  end
  W -- "Bearer NOTION_TOKEN" --> N["api.notion.com"]
```

There are three layers of auth, and each has one job:

| Layer | Decides | Configured in |
|---|---|---|
| Portal Access app (`mcp_portal`) | Who may use the portal at all (your email; a service token for agents) | Zero Trust → Access controls → Applications |
| Server Access app (`mcp`) | Who may reach the Worker's hostname; the portal authenticates to it once, as you | Zero Trust → Access controls → Applications |
| Worker JWT check | Rejects anything that didn't come through Access, even if a route is misconfigured | `ACCESS_AUD` in `wrangler.jsonc` |

## Tools

| Tool | What it does |
|---|---|
| `notion_find_endpoints` | Keyword search over the bundled Notion OpenAPI spec (top 8 matches). Pass `operation_id` to get one endpoint's full parameter and body schema, with `$ref`s resolved. |
| `notion_request` | Calls any Notion API endpoint (`method`, `path`, `query`, `body`). Returns compact results by default: nulls, property and option ids, and rich-text formatting are dropped. `format: "values"` returns each row as `{ id, url, last_edited_time, props: { Name: value } }` with empty properties left out and formulas and rollups computed; `format: "raw"` returns Notion's full JSON. Page Markdown comes back as plain Markdown. A list over 24,000 characters is fetched again with a smaller `page_size` (reported as `page_size_reduced_to`), so rows are whole and `next_cursor` skips nothing; other long reads end with a marker giving the `offset` for the next part. A query array repeats the key, so `{ filter_properties: ["Name", "Status"] }` returns only those properties. Sets the right `Notion-Version` per endpoint, retries 429s (and, for reads, 5xx and network failures), caches database and data source schemas for 5 minutes, and returns Notion's error code and message plus a `[class=…; retryable|not retryable]` tag so the model can self-correct. |
| `governance_bundle` | *Optional; listed only when `GOVERNANCE_README_ID` is set.* One read-only call for what an agent loads at session start: the governance README's Markdown, the Activity Log's field list (name, type, options, description), and the `Adopted` Preferences rows for a `scope` plus `Whole workspace` (`Preference`, `Strength`, `Scope` only). Optional `guides` and `schemas` (up to 3 names each) add guide pages and store field lists; optional `sections` picks which of `readme`, `activity_log_fields` and `preferences` come back (`[]` = only the named guides and schemas). Everything is read live on every call (no schema cache). Stores and guides are found through the README's own tables, so no IDs live in code. `errors` is always the first key: a part that couldn't be read is `null` with its reason there, and an unknown `scope` lists the valid ones. A bundle over 24,000 characters stays valid JSON: whole sections go in (the core first, then schemas, then guides) and the rest is named in `pending`, which is exactly the arguments of the call that returns it. A single guide or README too long for any reply is `null`, with the `notion_request` call that reads it in `errors`. |

Two generic tools cover the whole API, so the tool list stays small. The model looks an endpoint up, then calls it. `governance_bundle` is the one purpose-built exception, for a workspace that keeps its agent rules in Notion.

Each Notion call writes one `notion_call` log line (method, path, status, `ms`, retries, whether the schema cache answered) to Workers Logs, so you can see where time goes. Paths include page and data source IDs; query strings, bodies and the token are never logged.

## Security model

- **Fail closed.** If `ACCESS_TEAM_DOMAIN` or `ACCESS_AUD` is unset, or the `Cf-Access-Jwt-Assertion` doesn't verify against your team's JWKS (issuer and audience), the Worker returns 401. Only `/health` is open.
- **No bypass URLs.** `workers_dev` and `preview_urls` are off, so the Worker is reachable only on the hostname Access protects.
- **Requests are pinned to Notion.** Paths must start with `/v1/` and must resolve to `api.notion.com`.
- **Least privilege lives in Notion.** The integration sees only pages you share with it. Share the minimum.
- **Redirect allowlists stay explicit.** Managed OAuth's Dynamic Client Registration only accepts listed callback URLs. Never allow all: the allowlist is what stops a stranger's client from receiving your tokens.

One limitation: every portal user acts as the same Notion integration (a workspace bot), not as their own Notion account. This is fine for one person and their agents. It is not multi-tenant.

## Setup

See **[docs/SETUP.md](docs/SETUP.md)**. In short:

1. Create a Notion internal integration and share pages with it.
2. Deploy the Worker and set the `NOTION_TOKEN` secret.
3. Protect its hostname with an Access app (type MCP) using Managed OAuth, then set `ACCESS_AUD` and redeploy.
4. Register it as an MCP server in Zero Trust and authenticate it.
5. Add it to an MCP server portal and allowlist your clients' callbacks.
6. Connect Claude (or anything else) to `https://mcp.example.com/mcp`.
7. Optional: give headless agents a service token.
8. Optional: set `GOVERNANCE_README_ID` (below) to turn on `governance_bundle`.

### Optional: `governance_bundle`

Set `vars.GOVERNANCE_README_ID` in `wrangler.jsonc` to the Notion page ID of your agents' README, and redeploy. Without it the tool isn't listed, so it costs no tokens. The tool reads two tables from that page, found by heading and by column header (column order doesn't matter):

- `## Where things go`: one row per store. The store's name is the link text in the row (`[Activity Log](https://…)`), and its `Data source` column holds `` `collection://<data source id>` ``. Rows named `Activity Log` and `Preferences` are required.
- `## Guides`: a `Guide` column of links (`[Tool Guide](https://…/<page id>)`).

Preferences is expected to have a `Status` select (rows with `Adopted` are returned), a `Scope` multi-select (including a `Whole workspace` option), and `Preference` and `Strength` properties. The names are constants at the top of `src/governance.ts` and `src/readme-tables.ts`; change them there if your workspace uses others.

Things break in specific, non-obvious ways along the way. **[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** lists every one I hit, with the fix.

## Local development

```bash
npm ci
cp wrangler.example.jsonc wrangler.jsonc   # your config; gitignored
npm run check   # type-check + wrangler dry-run build
npm run dev     # local server on test/dev-entry.ts with a fake token
```

`test/dev-entry.ts` skips the Access check so you can exercise the MCP handler locally. Never deploy it.

`npm run dev` needs the `workerd` binary. If your npm version blocks install scripts, approve `workerd`'s postinstall when npm asks.

## Releasing

Before merging a release PR, all of these must pass:

1. CI green, plus `npm run check`, `npm test` and `npm run test:e2e` locally.
2. `npm run smoke` against a local Worker (`SMOKE_EXPECT_VERSION=<new version>`; setup is in the file header).
3. A live double scan of every list the agents read, with `test/scan.mjs` (`SCAN_DATA_SOURCE_ID`, `SCAN_DELAY_MS` of 1000 or more). Both scans must agree, with no lost cursor, cut row or duplicate. Run it outside scheduled-job windows.

After `wrangler deploy`:

4. An unauthenticated request to `/mcp` returns 401.
5. `wrangler tail` shows no exceeded-CPU outcomes or exceptions.
6. One authenticated scan through the portal succeeds. The scheduled agents' next runs are the longer check.
7. Record the release wherever you track the project (a status page, handoff note or issue): the version, the deployed version id, the previous id for rollback, and anything left open. A deploy with no record is easy to lose, and the tracker then names the old version.

Rollback: redeploy the previous release commit. The deploy ids are in the release notes.

Two things that cost a step in practice:

- GitHub deletes a PR's branch when it merges, so run `git fetch --prune` before listing "stale" remote branches.
- When logging `wrangler tail --format json` through `jq` into a file, use `jq --unbuffered`; otherwise the file stays empty until the buffer fills.

## License

MIT. `src/notion-openapi.json` comes from [makenotion/notion-mcp-server](https://github.com/makenotion/notion-mcp-server) (MIT); see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).