Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "https://unpkg.com/@changesets/config/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": [],
"privatePackages": { "version": true, "tag": true }
}
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
CLOUDFLARE_ACCOUNT_ID=
# Only for `just access`: an API token with Access: Apps and Policies Write.
# Not named CLOUDFLARE_API_TOKEN, so wrangler keeps using your own login to deploy.
ACCESS_API_TOKEN=
CLAIRIC_DOMAIN=clairic.example.com
ACCESS_TEAM_DOMAIN=yourteam.cloudflareaccess.com
# Comma-separated Access login emails allowed to connect
ACCESS_EMAILS=you@example.com
# Optional identity provider id; empty allows every login method the team has
ACCESS_IDP_ID=
# Written by `just access`
ACCESS_AUD=
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
cooldown:
default-days: 7
groups:
actions:
patterns: ["*"]
49 changes: 49 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: ci

on:
pull_request:
push:
branches: [main]
merge_group:

permissions: {}

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
linux:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: pnpm
uses: pnpm/setup@a0881977cd8ea73b1ed212236c99ca10dcc80cf4 # v3.1.1
with:
cache: true
require-lockfile: true
- name: tools
uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2.87.28
with:
tool: zizmor
fallback: none
- name: format
run: pnpm exec oxfmt --check
- name: lint
run: pnpm exec oxlint --format github
- name: types
run: pnpm exec tsc --noEmit
- name: test
run: pnpm exec vitest run
- name: workflows
env:
GH_TOKEN: ${{ github.token }}
run: |
zizmor --format=github .
go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12
58 changes: 58 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Pending changesets open a version PR that merges itself once CI passes; the merge
# tags the release. The App token is what lets those events trigger CI and this
# workflow again, which GITHUB_TOKEN events do not.
name: release

on:
push:
branches: [main]

permissions: {}

jobs:
release:
# Copies without a release App of their own skip releasing.
if: vars.RELEASE_APP_CLIENT_ID != ''
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: harden runner
uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
with:
egress-policy: audit
- name: token
id: app
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
with:
client-id: ${{ vars.RELEASE_APP_CLIENT_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
permission-contents: write
permission-pull-requests: write
- name: checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# changeset version reads history to date each changeset; a shallow clone would refetch without credentials.
fetch-depth: 0
- name: pnpm
uses: pnpm/setup@a0881977cd8ea73b1ed212236c99ca10dcc80cf4 # v3.1.1
with:
cache: false
require-lockfile: true
- name: changesets
id: changesets
uses: changesets/action@ae32849d5ba541f9ae29e40e22a623bc13562f51 # v2.1.2
with:
github-token: ${{ steps.app.outputs.token }}
version-script: pnpm run release:version
publish-script: pnpm changeset git-tag
pr-title: "chore: release"
commit-message: "chore: release"
- name: automerge
if: steps.changesets.outputs.pr-number != ''
env:
GH_TOKEN: ${{ steps.app.outputs.token }}
PR: ${{ steps.changesets.outputs.pr-number }}
run: gh pr merge --auto --squash "$PR"
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,10 @@ vite.config.ts.timestamp-*

# Turbo Repo
.turbo

# wrangler
.wrangler/
.dev.vars*

# generated by wrangler types on install
worker-configuration.d.ts
24 changes: 24 additions & 0 deletions .oxfmtrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"useTabs": true,
"printWidth": 80,
"sortPackageJson": true,
"sortImports": {
"groups": [
["type"],
["builtin", "external"],
["internal", "subpath"],
["parent", "sibling", "index"]
],
"newlinesBetween": true
},
"overrides": [
{ "files": ["**/*.jsonc"], "options": { "trailingComma": "none" } }
],
"ignorePatterns": [
"worker-configuration.d.ts",
"test/fixtures/**",
"prek.toml",
"**/*.md"
]
}
17 changes: 17 additions & 0 deletions .oxlintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["unicorn", "oxc", "typescript", "vitest", "import", "promise"],
"options": { "typeAware": true, "reportUnusedDisableDirectives": "warn" },
"categories": {
"correctness": "error",
"suspicious": "error",
"perf": "warn"
},
"rules": {
"eqeqeq": "error",
"unicorn/filename-case": ["error", { "case": "kebabCase" }],
"id-denylist": ["error", "data", "result", "temp", "info", "tmp", "val"],
"no-await-in-loop": "off"
},
"ignorePatterns": ["worker-configuration.d.ts"]
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Luis Markmann

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# clairic-mcp

An MCP server that gives you Cloudflare's [Clairic](https://developers.cloudflare.com/workers-ai/models/clairic/) model as one tool, `extract`. It runs as a Worker on your own Cloudflare account, behind Cloudflare Access.

You send `extract` an input (text, a public web page or up to four images) and a list of fields, each with a name and a type. Clairic gives back one answer per field: a value of that type, or null when the input doesn't settle it. Each answer carries a `confidence`, the chance the value is right, and a `p_null`, the chance the input has no value for the field. Text answers also say which line they came from. Clairic answers in one fast pass and doesn't reason step by step, so the assistant calling it picks the fields and does any arithmetic longer than a step or two.

## Setup

You need:

- a Cloudflare account with a domain on it
- a Zero Trust team, which is free, with at least one login method (One-time PIN is enough)
- an API token with **Access: Apps and Policies Write**, used once by `just access`
- Node 24, pnpm, [just](https://github.com/casey/just), curl and jq

```sh
git clone https://github.com/lmarkmann/clairic-mcp && cd clairic-mcp
pnpm install
pnpm exec wrangler login
cp .env.example .env # your account id, domain, team, allowed emails and the API token
just access # creates the Access app and policy, writes ACCESS_AUD to .env
just deploy # runs the checks, then deploys to your domain
```

Everything specific to your deployment lives in `.env`, which git ignores. The Worker rejects every request until `ACCESS_AUD` is set, so a deploy without `just access` serves nothing.

Access sits in front of the whole hostname and acts as the OAuth server: a client registers itself, sends you to your team's login page, and only emails on the `clairic-mcp users` policy get through.

## Connect

Claude Code:

```sh
claude mcp add --transport http clairic https://<your domain>/mcp
```

pi:

```sh
pi mcp add clairic --url https://<your domain>/mcp
```

Then sign in when the client asks (`/mcp` in either one). Other clients take the same URL as a remote MCP server with the client ID and secret left empty. Access accepts callbacks on localhost and the hosted callback listed under `allowed_uris` in the `justfile`; add any other hosted callback there before you run `just access`.

Clients keep the tool list from when they connected, so reconnect after an update changes the tool.

## Example

The input:

```
Invoice INV-2291 from Northwind Supply, issued 2026-09-02, net 30.
4 pallets at $250.00 each, shipping $80.00.
```

The fields:

```json
{
"due_date": { "type": "date", "instructions": "Issue date plus the net payment days" },
"total": { "type": "number", "decimals": 2, "unit": "USD", "instructions": "Amount due including shipping" },
"po_number": { "type": "text", "instructions": "Purchase order number" },
"days_to_pay": { "type": "estimate", "min": 0, "max": 120, "step": 1, "instructions": "Days after issue until this invoice is paid" }
}
```

The answers:

```
due_date: "2026-10-02" (confidence >0.999, p_null <0.001)
total: 1080 USD (confidence >0.999, p_null <0.001)
po_number: null (p_null >0.999; best guess "INV-2291" at confidence >0.999)
days_to_pay: 31 (median 31, 80% interval 24 to 38, mean 31.32)
```

The due date and the total are computed, not copied. The invoice has no purchase order number, so `po_number` is null; the best guess next to it is what Clairic would say if forced to pick, not an answer. An answer with confidence under 0.9, or a p_null between 0.1 and 0.9, is marked `[check]`, and the tool tells the client to have you verify it.

## Field types

| Type | You get |
| --- | --- |
| `text` | A piece of the input, quoted as written, with its line number |
| `number`, `duration` | A number, optionally with a unit, fixed decimals or a whole number |
| `date`, `time`, `datetime` | An ISO value; dates without a year are read relative to the reference date |
| `list` | Every match, as text, numbers or dates |
| `estimate` | A median and an 80% interval between the `min` and `max` you set |
| `forecast` | One estimate per step ahead, from a series in the input |
68 changes: 68 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
set dotenv-load

# Create the Access policy and application that guard the Worker, then store the app's AUD in .env
access:
#!/usr/bin/env bash
set -euo pipefail
: "${CLOUDFLARE_ACCOUNT_ID:?set it in .env}" "${ACCESS_API_TOKEN:?set it in .env or the environment}"
: "${CLAIRIC_DOMAIN:?set it in .env}" "${ACCESS_EMAILS:?set it in .env}"
if [ -n "${ACCESS_AUD:-}" ]; then
echo "ACCESS_AUD is already set in .env, so the Access application exists. Clear it to create another." >&2
exit 1
fi
api="https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/access"
post() {
local reply
if ! reply=$(curl -sS --fail-with-body -X POST "$api/$1" \
-H "Authorization: Bearer $ACCESS_API_TOKEN" -H "Content-Type: application/json" --data "$2"); then
echo "POST $1 failed: $reply" >&2
return 1
fi
echo "$reply"
}
policy_body=$(jq -cn --arg emails "$ACCESS_EMAILS" '{
name: "clairic-mcp users",
decision: "allow",
include: ($emails | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(. != "")) | map({email: {email: .}}))
}')
policy=$(post policies "$policy_body" | jq -r .result.id)
echo "Created Access policy $policy" >&2
# A policy left without its application would be duplicated by the next run, since ACCESS_AUD stays empty.
trap 'echo "Deleting Access policy $policy" >&2; curl -sS -o /dev/null -X DELETE "$api/policies/$policy" -H "Authorization: Bearer $ACCESS_API_TOKEN"' ERR
app_body=$(jq -cn --arg domain "$CLAIRIC_DOMAIN" --arg policy "$policy" --arg idp "${ACCESS_IDP_ID:-}" '{
name: "clairic-mcp",
type: "self_hosted",
domain: $domain,
destinations: [{type: "public", uri: $domain}],
policies: [{id: $policy, precedence: 1}],
session_duration: "24h",
oauth_configuration: {
enabled: true,
grant: {session_duration: "336h", access_token_lifetime: "15m"},
dynamic_client_registration: {
enabled: true,
allowed_uris: ["https://claude.ai/api/mcp/auth_callback"],
allow_any_on_localhost: true,
allow_any_on_loopback: true
}
}
} + (if $idp == "" then {} else {allowed_idps: [$idp], auto_redirect_to_identity: true} end)')
app=$(post apps "$app_body")
trap - ERR
echo "Created Access application $(jq -r .result.id <<< "$app") on $CLAIRIC_DOMAIN" >&2
{ grep -v '^ACCESS_AUD=' .env || true; echo "ACCESS_AUD=$(jq -r .result.aud <<< "$app")"; } > .env.next
mv .env.next .env

# Check, test and deploy the Worker to CLAIRIC_DOMAIN behind the Access application
ci:
pnpm exec oxfmt --check .
pnpm exec oxlint
pnpm exec tsc --noEmit -p .
pnpm exec vitest run

deploy: ci
#!/usr/bin/env bash
set -euo pipefail
: "${CLAIRIC_DOMAIN:?set it in .env}" "${ACCESS_TEAM_DOMAIN:?set it in .env}" "${ACCESS_AUD:?run just access first}"
pnpm exec wrangler deploy --domain "$CLAIRIC_DOMAIN" \
--var "ACCESS_TEAM_DOMAIN:$ACCESS_TEAM_DOMAIN" --var "ACCESS_AUD:$ACCESS_AUD"
Loading
Loading