Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
3c44437
Point MCP clients at the Writebook to sign in with
monorkin Nov 30, 2026
af38cd6
Describe OAuth discovery in the README and skill, and drop narrating …
monorkin Nov 30, 2026
2068908
Follow RFC 9728's resource paths, refuse metadata without a Host, and…
monorkin Nov 30, 2026
dd5bcb5
Check the scopes and bearer methods the resource metadata advertises
monorkin Nov 30, 2026
fc9d5da
Leave the skill out of the discovery change
monorkin Nov 30, 2026
fe3193e
Say to run the MCP server yourself, since tokens pass through it
monorkin Nov 30, 2026
a9eec63
Keep the server's answer out of the no-Host test's message
monorkin Nov 30, 2026
cd672ee
Ask for the admin scope, and say to sign in again when a sign-in lack…
monorkin Nov 30, 2026
464adfd
Sign in to Writebooks from before the admin scope, and word a refusal…
monorkin Nov 30, 2026
986ae17
Answer 401 for a token Writebook turns away, word refusals by the mis…
monorkin Nov 30, 2026
ceb3fe0
Answer health checks at /up, and show how to run the MCP server behin…
monorkin Nov 30, 2026
46f3642
Move the proxy setup out of the README into doc/mcp-server.md
monorkin Nov 30, 2026
924862f
Serve MCP on port 80 by default in the image, with settings from envi…
monorkin Nov 30, 2026
5ba8e36
Fix the review's findings: test scope refusals, the token check and t…
monorkin Nov 30, 2026
24437be
Move HTTP serving to mcp serve --bind, and fix the second review's fi…
monorkin Nov 30, 2026
9881e15
Tell an administrator whose sign-in can't manage people how to sign i…
monorkin Nov 30, 2026
8f32285
Document running the MCP server with ONCE first, and write the docs a…
monorkin Nov 30, 2026
cac3978
Fix the third review's findings
monorkin Nov 30, 2026
9fffdfc
Exchange agents' tokens with Writebook instead of passing them through
monorkin Nov 30, 2026
d7ffcea
Fix the review's findings on the token exchange
monorkin Nov 30, 2026
5c547bb
Forget an exchanged token Writebook rejects, so the next request gets…
monorkin Nov 30, 2026
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
11 changes: 7 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@

# The writebook CLI, mainly for serving a Writebook to MCP clients:
#
# docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli \
# mcp --instance https://books.example.com --serve 0.0.0.0:8080
# docker run -p 8080:80 \
# -e WRITEBOOK_MCP_INSTANCE=https://books.example.com \
# -e WRITEBOOK_MCP_PUBLIC_URL=https://mcp.example.com \
# -e WRITEBOOK_MCP_SECRET=<secret> \
# ghcr.io/basecamp/writebook-cli

ARG RUST_VERSION=1.99
FROM docker.io/library/rust:${RUST_VERSION}-slim-trixie AS build
Expand Down Expand Up @@ -39,6 +42,6 @@ COPY --from=build /usr/local/bin/writebook /usr/local/bin/writebook

USER writebook
ENV WRITEBOOK_NO_KEYRING=1
EXPOSE 8080
EXPOSE 80
ENTRYPOINT ["writebook"]
CMD ["--help"]
CMD ["mcp", "serve", "--bind", "0.0.0.0:80"]
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,12 @@ It can also be used as a server to give anyone's agent access to a Writebook
instance using their own logins:

```sh
writebook mcp --instance https://books.example.com --serve 127.0.0.1:8080
WRITEBOOK_MCP_SECRET=<secret> writebook mcp serve \
--instance https://books.example.com --public-url https://mcp.example.com
```

Or run it with Docker:

```sh
docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp --instance https://books.example.com --serve 0.0.0.0:8080
```
[doc/mcp-server.md](doc/mcp-server.md) explains how to set it up, with ONCE or
behind a proxy.

To browse your books in the terminal, and add, delete, move and publish
pages, run:
Expand Down
88 changes: 88 additions & 0 deletions doc/mcp-server.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Running the MCP server

`writebook mcp serve` gives agents access to one Writebook instance over HTTP.
Each agent signs in to your Writebook with OAuth, and Writebook issues it a
token that only this MCP server accepts. The server exchanges that token with
Writebook for a short-lived one, and uses that to read and change books.

Give the server its own host name, like `mcp.example.com`. MCP clients look
for its sign-in details at `/.well-known/oauth-protected-resource/mcp` on that
host.

The server and your Writebook share a secret of at least 32 characters. Make
one with:

```sh
openssl rand -hex 32
```

## With ONCE

ONCE is the easiest way to run the server. It handles TLS for you.

Tell your Writebook about the server. `--env` replaces the app's environment
variables, so include any you already set:

```sh
once update books.example.com \
--env MCP_SERVER_URL=https://mcp.example.com/mcp \
--env MCP_SERVER_SECRET=<the secret>
```

Then deploy the server:

```sh
once deploy ghcr.io/basecamp/writebook-cli --host mcp.example.com \
--env WRITEBOOK_MCP_INSTANCE=https://books.example.com \
--env WRITEBOOK_MCP_PUBLIC_URL=https://mcp.example.com \
--env WRITEBOOK_MCP_SECRET=<the secret>
```

The Docker image runs the server on port 80 by default. It reads its settings
from these environment variables:

- `WRITEBOOK_MCP_INSTANCE`: the URL of your Writebook.
- `WRITEBOOK_MCP_PUBLIC_URL`: the server's https address. Your Writebook's
`MCP_SERVER_URL` is this address followed by `/mcp`.
- `WRITEBOOK_MCP_SECRET`: the secret, the same as your Writebook's
`MCP_SERVER_SECRET`.
- `WRITEBOOK_MCP_READ_ONLY=true`: serve only the tools that read.

The server checks the secret with your Writebook when it starts, and stops if
Writebook doesn't accept it.

## Behind another proxy

Set `MCP_SERVER_URL` and `MCP_SERVER_SECRET` on your Writebook as above, then
start the server with the same settings, as flags or environment variables:

```sh
WRITEBOOK_MCP_SECRET=<the secret> writebook mcp serve \
--instance https://books.example.com --public-url https://mcp.example.com
```

The secret can only be set with the environment variable.

The server uses plain HTTP and listens on `127.0.0.1:8080`, so put it behind a
proxy that handles TLS. The proxy must pass on the `Authorization` header.
`GET /up` returns 200 without a token. Use it for health checks.

With kamal-proxy, deploy it as it is, without `--path-prefix`. With Caddy:

```
mcp.example.com {
reverse_proxy 127.0.0.1:8080
}
```

With Apache, turn on `mod_proxy` and `mod_proxy_http`:

```apache
<VirtualHost *:443>
ServerName mcp.example.com
# your TLS settings

ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>
```
17 changes: 11 additions & 6 deletions skills/writebook/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ the user. It fails, and the error message says which command to run.
If you only need to read books, add `--read-only` in step 1. The sign-in can
read books but can't change them, so `push` fails. The approval page tells
the user that the device will only be able to read.

An administrator who wants to manage people and settings in `writebook tui`
must tick "Manage people and settings" on the approval page.
In `writebook tui`, creating a book needs a sign-in that can write: a
read-only one isn't offered "new book".

Expand Down Expand Up @@ -284,13 +287,15 @@ claude mcp add writebook -- writebook mcp
To give other people's agents access to one instance, run it as a server:

```sh
writebook mcp --instance https://books.example.com --serve 0.0.0.0:8080
WRITEBOOK_MCP_SECRET=<secret> writebook mcp serve \
--instance https://books.example.com --public-url https://mcp.example.com
```

The server doesn't use the user's sign-in. Each request must send a Writebook
token as a Bearer header. The server sends the token only to that instance. The
server uses plain HTTP, so put it behind https unless it listens only on this
computer. The Docker image `ghcr.io/basecamp/writebook-cli` runs the same
command.
The server doesn't use the user's sign-in. Agents sign in to the instance with
OAuth, and the instance issues them tokens that only this server accepts. The
instance needs `MCP_SERVER_URL` set to the public URL followed by `/mcp`, and
`MCP_SERVER_SECRET` set to the same secret. The server uses plain HTTP, so put
it behind https. The Docker image `ghcr.io/basecamp/writebook-cli` runs this
server on port 80 unless you give it another command.

If you already use the CLI, you don't need the MCP server.
83 changes: 76 additions & 7 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,59 @@ impl std::fmt::Display for ApiError {

impl std::error::Error for ApiError {}

#[derive(Debug)]
pub struct ScopeTooNarrow {
pub missing: MissingScope,
sign_in: Option<String>,
}

#[derive(Debug, PartialEq)]
pub enum MissingScope {
Write,
Admin,
Unnamed,
}

impl MissingScope {
// https://www.rfc-editor.org/rfc/rfc6750#section-3
fn from_challenge(challenge: &str) -> MissingScope {
match challenge.split("scope=\"").nth(1).and_then(|it| it.split('"').next()) {
Some(scope) if scope.split(' ').any(|it| it == "admin") => MissingScope::Admin,
Some(_) => MissingScope::Write,
None => MissingScope::Unnamed,
}
}
}

impl std::fmt::Display for ScopeTooNarrow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (refusal, approval) = match self.missing {
MissingScope::Write => (
"can only read, so it can't change books",
"approve reading and changing books",
),
MissingScope::Admin => (
"can't manage people and settings",
"tick \"Manage people and settings\"",
),
MissingScope::Unnamed => ("wasn't given access to do that", "approve the access it needs"),
};

match &self.sign_in {
Some(sign_in) => write!(
f,
"Writebook says this sign-in {refusal}. Sign in again with `{sign_in}` and {approval}"
),
None => write!(
f,
"Writebook says the token in WRITEBOOK_TOKEN {refusal}. Use a token that has the access it needs"
),
}
}
}

impl std::error::Error for ScopeTooNarrow {}

/// The site turned the token away.
#[derive(Debug)]
pub struct TokenRejected {
Expand Down Expand Up @@ -205,18 +258,17 @@ impl Client {
}

fn request(&mut self, path: &str, request: Request) -> Result<Value> {
response_json(path, self.send_renewing(|client| client.send(path, &request))?)
let response = self.send_renewing(|client| client.send(path, &request))?;
response_json(&self.host, path, response)
}

fn multipart(&mut self, path: &str, method: MultipartMethod, parts: &[Part]) -> Result<Value> {
let boundary = multipart_boundary();
let body = multipart_body(&boundary, parts);
let content_type = format!("multipart/form-data; boundary={boundary}");

response_json(
path,
self.send_renewing(|client| client.send_multipart(path, method, &content_type, &body))?,
)
let response = self.send_renewing(|client| client.send_multipart(path, method, &content_type, &body))?;
response_json(&self.host, path, response)
}

fn send_renewing(&mut self, send: impl Fn(&Client) -> Result<Response>) -> Result<Response> {
Expand Down Expand Up @@ -347,10 +399,27 @@ pub fn url_on(host: &str, path: &str) -> Result<String> {
}
}

fn response_json(path: &str, mut response: Response) -> Result<Value> {
fn response_json(host: &str, path: &str, mut response: Response) -> Result<Value> {
let status = response.status().as_u16();
let text = response.body_mut().read_to_string();
let challenge = response
.headers()
.get("www-authenticate")
.and_then(|it| it.to_str().ok())
.filter(|it| it.contains("insufficient_scope"))
.map(str::to_string);

if let (403, Some(challenge)) = (status, challenge) {
Err(ScopeTooNarrow {
missing: MissingScope::from_challenge(&challenge),
sign_in: creds::sign_in_again_command(host),
}
.into())
} else {
answer_json(path, status, response.body_mut().read_to_string())
}
}

fn answer_json(path: &str, status: u16, text: Result<String, ureq::Error>) -> Result<Value> {
if (200..300).contains(&status) {
let text = text.with_context(|| format!("could not read the answer to {path}"))?;

Expand Down
46 changes: 38 additions & 8 deletions src/creds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ pub fn normalize_host(host: &str) -> String {
host.trim().trim_end_matches('/').to_lowercase()
}

fn is_local(host: &str) -> bool {
pub fn is_local(host: &str) -> bool {
let name = host.trim_start_matches("http://").split(':').next().unwrap_or_default();
matches!(name, "localhost" | "127.0.0.1") || host.trim_start_matches("http://").starts_with("[::1]")
}
Expand Down Expand Up @@ -304,6 +304,19 @@ impl std::fmt::Display for RenewalFailed {

impl std::error::Error for RenewalFailed {}

/// The command that signs the current profile in again, unless the token
/// came from WRITEBOOK_TOKEN, which signing in again wouldn't change.
pub fn sign_in_again_command(host: &str) -> Option<String> {
if GIVEN_TOKEN.get().is_some() {
None
} else {
match inventory::profile_for(host) {
Ok(profile) => Some(inventory::sign_in_command(host, &profile)),
Err(_) => Some(format!("writebook instance add {host}")),
}
}
}

pub fn rejected_token_advice(host: &str) -> String {
if GIVEN_TOKEN.get().is_some() {
"Check WRITEBOOK_TOKEN".to_string()
Expand Down Expand Up @@ -483,21 +496,38 @@ fn access_from(body: &Value) -> Access {
}

fn request_device_authorization(host: &str, access: Access) -> Result<Value> {
let scope = match access {
Access::Full => "read write",
Access::ReadOnly => "read",
let (status, body) = match access {
Access::ReadOnly => post_device_authorization(host, "read")?,
Access::Full => match post_device_authorization(host, "read write admin")? {
(400, body) if body["error"] == "invalid_scope" => post_device_authorization(host, "read write")?,
answer => answer,
},
};

if status == 200 {
Ok(body)
} else {
bail!("{host} does not support device sign-in — is it running a Writebook with the CLI API?")
}
}

fn post_device_authorization(host: &str, scope: &str) -> Result<(u16, Value)> {
let mut response = api::agent()
.post(&format!("{host}/oauth/device_authorizations"))
.send_form([("client_id", CLIENT_ID), ("scope", scope)])
.with_context(|| format!("could not reach {host}"))?;

if response.status() != 200 {
bail!("{host} does not support device sign-in — is it running a Writebook with the CLI API?");
}
let status = response.status().as_u16();

Ok(response.body_mut().read_json()?)
if status == 200 {
let body = response
.body_mut()
.read_json()
.with_context(|| format!("{host} sent a device sign-in answer the CLI can't read"))?;
Ok((status, body))
} else {
Ok((status, response.body_mut().read_json().unwrap_or(Value::Null)))
}
}

fn post_token_request(host: &str, form: &[(&str, &str)]) -> Result<(u16, Value)> {
Expand Down
Loading