bookstack-mcp 5.4.1 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PRIVACY.md +159 -0
- package/README.md +66 -1
- package/dist/bookstack-client.js +80 -57
- package/dist/image-source.js +85 -0
- package/dist/index.js +78 -23
- package/dist/oauth/entra-proxy.js +17 -13
- package/dist/request-credentials.js +39 -0
- package/dist/util/rate-limit.js +81 -0
- package/dist/util/safe-errors.js +55 -0
- package/dist/util/semaphore.js +21 -4
- package/package.json +6 -5
package/PRIVACY.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# Privacy policy for bookstack-mcp
|
|
2
|
+
|
|
3
|
+
Last reviewed: 2026-10-09.
|
|
4
|
+
|
|
5
|
+
This policy describes the data handling implemented by the open-source
|
|
6
|
+
`bookstack-mcp` application in this repository. It applies to the software you
|
|
7
|
+
run locally or deploy on a server. A deployment operator, BookStack instance,
|
|
8
|
+
MCP client, AI provider, or other service may have additional data practices and
|
|
9
|
+
policies. This document does not establish those services' retention periods or
|
|
10
|
+
make commitments on their behalf.
|
|
11
|
+
|
|
12
|
+
The error-handling protections described below were merged in
|
|
13
|
+
[PR #47](https://github.com/ttpears/bookstack-mcp/pull/47) at security commit
|
|
14
|
+
[`35b218c5e7eca129ab94ad8f8b89275815697e3c`](https://github.com/ttpears/bookstack-mcp/commit/35b218c5e7eca129ab94ad8f8b89275815697e3c).
|
|
15
|
+
This policy does not imply that an existing package, image or deployment already
|
|
16
|
+
includes those changes. Check the source revision of the version you run.
|
|
17
|
+
|
|
18
|
+
## Data processed and where it goes
|
|
19
|
+
|
|
20
|
+
- **BookStack:** The application sends API requests to `BOOKSTACK_BASE_URL`,
|
|
21
|
+
including the configured API token ID and secret in an authorization header.
|
|
22
|
+
Requests can include search queries, identifiers, filters and, when write
|
|
23
|
+
tools are enabled, content, metadata, comments or image uploads. Responses can
|
|
24
|
+
contain private wiki content, attachment or export links, and user information
|
|
25
|
+
such as names and email addresses, subject to BookStack permissions.
|
|
26
|
+
- **MCP client:** Tool results and resources are returned to the connected MCP
|
|
27
|
+
client. The client can supply them to an AI provider or retain them in chat
|
|
28
|
+
history or logs under its own settings and policies. Read-only mode prevents
|
|
29
|
+
write tools from being registered; it does not prevent content from reaching
|
|
30
|
+
the client.
|
|
31
|
+
- **Image sources:** An enabled image-upload tool can read a caller-specified
|
|
32
|
+
local image file or download an HTTP(S) image, then upload its bytes to
|
|
33
|
+
BookStack. The image host receives the URL request and normal connection
|
|
34
|
+
information. Local file access is enabled in stdio mode; in HTTP mode it
|
|
35
|
+
requires `BOOKSTACK_ALLOW_LOCAL_IMAGE_FILES=true`. HTTP image downloads are
|
|
36
|
+
restricted by `BOOKSTACK_IMAGE_ALLOWED_HOSTS`; stdio mode has no such host
|
|
37
|
+
restriction by default. These operations also require write tools to be
|
|
38
|
+
enabled.
|
|
39
|
+
- **Optional Microsoft Entra ID:** With `MCP_OAUTH_ENABLE=true`, the application
|
|
40
|
+
redirects sign-in to the configured Microsoft tenant, exchanges authorization
|
|
41
|
+
codes and refresh tokens with Microsoft, and fetches signing keys to validate
|
|
42
|
+
bearer tokens. The proxy processes client IDs, redirect URIs, OAuth state and
|
|
43
|
+
PKCE values, token responses and token claims. It uses the subject and roles
|
|
44
|
+
to bind HTTP sessions and select configured BookStack credentials. Token
|
|
45
|
+
responses are returned to the requesting MCP client.
|
|
46
|
+
- **Optional Redis:** When OAuth is enabled and `REDIS_URL` is configured, OAuth
|
|
47
|
+
broker state is sent to that Redis instance. Its hosting, access controls,
|
|
48
|
+
persistence and backups are controlled by the operator.
|
|
49
|
+
|
|
50
|
+
The application code has no built-in usage analytics, crash-reporting service,
|
|
51
|
+
or automatic reporting of runtime wiki content to the project maintainers. It
|
|
52
|
+
does not call an AI model API itself. These statements describe the application
|
|
53
|
+
code, not the behavior of your MCP client, infrastructure or third-party
|
|
54
|
+
services.
|
|
55
|
+
|
|
56
|
+
## Local and server deployments
|
|
57
|
+
|
|
58
|
+
Stdio mode communicates with a client through the process's standard input and
|
|
59
|
+
output. The process still makes network requests to the configured BookStack
|
|
60
|
+
instance and, when used, remote image sources. HTTP mode accepts MCP requests
|
|
61
|
+
over an HTTP listener, which defaults to `127.0.0.1`. Remote hosting introduces
|
|
62
|
+
an operator and any configured proxies or infrastructure into the data path.
|
|
63
|
+
|
|
64
|
+
BookStack credentials are supplied through environment variables or client
|
|
65
|
+
configuration. HTTP clients can optionally supply credentials per request when
|
|
66
|
+
`BOOKSTACK_ALLOW_REQUEST_CREDENTIALS=true`; those credentials are used in a
|
|
67
|
+
request-scoped client rather than stored as HTTP session credentials. OAuth
|
|
68
|
+
client secrets and other configuration are also read from the environment.
|
|
69
|
+
Credential storage by the launcher, operating system, container platform or
|
|
70
|
+
secret manager is outside this application's control.
|
|
71
|
+
|
|
72
|
+
The HTTP listener does not implement TLS itself. Operators must provide suitable
|
|
73
|
+
authentication, HTTPS or a trusted internal connection, host restrictions and
|
|
74
|
+
least-privilege BookStack tokens. BookStack certificate verification can be
|
|
75
|
+
disabled by configuration; doing so reduces protection for credentials and
|
|
76
|
+
content in transit. See [SECURITY.md](./SECURITY.md).
|
|
77
|
+
|
|
78
|
+
## Memory, broker state and retention
|
|
79
|
+
|
|
80
|
+
Requests and responses are processed in memory. Book ID-to-slug mappings are
|
|
81
|
+
cached in memory, with a ten-minute bulk refresh interval; this is not a
|
|
82
|
+
guaranteed deletion deadline for individual cache entries. HTTP transports and,
|
|
83
|
+
in OAuth mode, subject/write-role bindings are held in memory. The default HTTP
|
|
84
|
+
session idle timeout is thirty minutes and is configurable; session closure,
|
|
85
|
+
expiry and process shutdown release the corresponding application state.
|
|
86
|
+
|
|
87
|
+
OAuth broker state uses process memory unless Redis is configured. The current
|
|
88
|
+
broker assigns time-to-live values of thirty days for client registrations,
|
|
89
|
+
ten minutes for pending authorization flows, and five minutes for issued codes
|
|
90
|
+
and their associated upstream token responses. Pending flows and issued codes
|
|
91
|
+
are deleted when consumed. In-memory expiration uses access-time checks and a
|
|
92
|
+
periodic sweep; Redis uses per-key expiry. These are application state lifetimes,
|
|
93
|
+
not promises about secure memory erasure, provider retention, Redis persistence
|
|
94
|
+
or backups.
|
|
95
|
+
|
|
96
|
+
The application does not implement a persistent wiki-content database or its own
|
|
97
|
+
log-file retention system. BookStack, MCP clients, proxies, hosting platforms and
|
|
98
|
+
operators may retain content, credentials, access records, logs or backups
|
|
99
|
+
independently. Consult those services and the deployment operator for retention
|
|
100
|
+
and deletion requests.
|
|
101
|
+
|
|
102
|
+
## Logs and error responses
|
|
103
|
+
|
|
104
|
+
Diagnostics are written to standard error. They include the BookStack and public
|
|
105
|
+
HTTP URL origins (without URL credentials, paths, queries or fragments), OAuth
|
|
106
|
+
tenant, abbreviated HTTP session IDs, session counts, export page IDs and
|
|
107
|
+
lengths, rate-limit retries, and authentication diagnostics.
|
|
108
|
+
|
|
109
|
+
With the security commit identified above, upstream BookStack and image-source
|
|
110
|
+
failures are converted to application-authored context, numeric HTTP status and
|
|
111
|
+
allowlisted error codes. These errors omit upstream bodies, headers, arbitrary
|
|
112
|
+
messages and nested causes. MCP tool handlers preserve explicitly marked local
|
|
113
|
+
validation messages; startup and HTTP error logs omit complete exception
|
|
114
|
+
objects. OAuth failure logs and responses use numeric status and allowlisted
|
|
115
|
+
OAuth codes rather than upstream bodies or descriptions; callback diagnostics
|
|
116
|
+
omit callback values and client IDs. Successful OAuth token responses and
|
|
117
|
+
normal tool results still carry their intended data to the requesting client.
|
|
118
|
+
|
|
119
|
+
**Earlier versions can expose sensitive data in errors.** Builds that do not
|
|
120
|
+
include the identified security commit can log upstream response excerpts,
|
|
121
|
+
descriptions, client IDs or full exception objects, and return upstream error
|
|
122
|
+
details to MCP clients. Library exceptions can contain credentials, request
|
|
123
|
+
headers, URLs or private response data.
|
|
124
|
+
|
|
125
|
+
These application protections do not guarantee that all logs are free of
|
|
126
|
+
credentials or private content. MCP clients, proxies, hosting platforms and
|
|
127
|
+
other infrastructure can collect their own logs. Operators should restrict log
|
|
128
|
+
access, configure collection and retention, and review and redact sensitive
|
|
129
|
+
material before sharing logs or error reports.
|
|
130
|
+
|
|
131
|
+
## Third-party services and project interactions
|
|
132
|
+
|
|
133
|
+
Installing packages or images involves the registries and distribution services
|
|
134
|
+
you choose. Viewing this repository, its badges, or linked documentation involves
|
|
135
|
+
GitHub, Shields.io, HOL or other linked services. The HOL CI workflow scans the
|
|
136
|
+
repository on a GitHub runner with online analysis, SARIF upload, submissions and
|
|
137
|
+
PR comments disabled; it downloads the scanner and dependencies during setup.
|
|
138
|
+
That workflow does not run as part of the installed MCP server.
|
|
139
|
+
|
|
140
|
+
Information you choose to submit through GitHub issues, pull requests or other
|
|
141
|
+
project channels is handled by those services. Do not include tokens or private
|
|
142
|
+
wiki content in public submissions. For a suspected vulnerability or sensitive
|
|
143
|
+
disclosure, follow [SECURITY.md](./SECURITY.md). For a question about this
|
|
144
|
+
software's data handling, use the existing
|
|
145
|
+
[project issue tracker](https://github.com/ttpears/bookstack-mcp/issues) without
|
|
146
|
+
including sensitive information. For a particular hosted deployment, contact
|
|
147
|
+
its operator rather than assuming the repository maintainer operates it.
|
|
148
|
+
|
|
149
|
+
## Operator responsibilities and changes
|
|
150
|
+
|
|
151
|
+
Operators choose the BookStack instance, credentials, permitted clients, write
|
|
152
|
+
access, image sources, OAuth tenant, optional Redis, network controls and log
|
|
153
|
+
handling. They should inform their users of deployment-specific processing and
|
|
154
|
+
third-party services, provide their own applicable policies and contact channel,
|
|
155
|
+
and handle access or deletion requests for systems they control.
|
|
156
|
+
|
|
157
|
+
This policy is versioned with the repository and may change when the
|
|
158
|
+
implementation changes. Review the policy and configuration for the version you
|
|
159
|
+
actually run.
|
package/README.md
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/bookstack-mcp)
|
|
4
4
|
[](https://www.npmjs.com/package/bookstack-mcp)
|
|
5
5
|
[](https://github.com/ttpears/bookstack-mcp/actions/workflows/ci.yml)
|
|
6
|
+
[](https://hol.org/registry/plugins/ttpears%2Fbookstack-mcp)
|
|
6
7
|
[](https://nodejs.org)
|
|
7
8
|
[](https://modelcontextprotocol.io)
|
|
8
9
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -15,11 +16,15 @@ A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server that gi
|
|
|
15
16
|
npx bookstack-mcp
|
|
16
17
|
```
|
|
17
18
|
|
|
19
|
+
Read the [privacy policy](./PRIVACY.md) for data flows, credentials, optional
|
|
20
|
+
OAuth/Redis state, and logging. Your MCP client and deployment operator may have
|
|
21
|
+
additional policies.
|
|
22
|
+
|
|
18
23
|
Field notes: [Why my BookStack MCP server starts read-only](https://hackyourworld.com/bookstack-mcp-server-read-only-by-default/) covers the shared-token rate-limit failure, process-wide cache, response-size measurements, and permission boundaries that shaped the current design.
|
|
19
24
|
|
|
20
25
|
## Features
|
|
21
26
|
|
|
22
|
-
-
|
|
27
|
+
- 21 read-only tools + 22 write tools for BookStack API access
|
|
23
28
|
- Books, chapters, pages, shelves, attachments, and comments — full CRUD
|
|
24
29
|
- Recycle bin support — restore or permanently delete soft-deleted content
|
|
25
30
|
- Type-safe input validation with Zod (auto-coerces string/number params for broad client compatibility)
|
|
@@ -55,8 +60,24 @@ BOOKSTACK_TOKEN_ID=your-token-id # Required
|
|
|
55
60
|
BOOKSTACK_TOKEN_SECRET=your-token-secret # Required
|
|
56
61
|
BOOKSTACK_ENABLE_WRITE=false # Optional, default false
|
|
57
62
|
BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=false # Optional, default false
|
|
63
|
+
BOOKSTACK_TIMEOUT_MS=30000 # Optional, timeout per HTTP attempt
|
|
64
|
+
BOOKSTACK_RETRY_TIMEOUT_MS=60000 # Optional, total budget per API request
|
|
58
65
|
```
|
|
59
66
|
|
|
67
|
+
Each API request has a total budget covering concurrency queue time, HTTP attempts,
|
|
68
|
+
and rate-limit backoff. HTTP 429 responses are retried up to five times, with each
|
|
69
|
+
delay capped at 30 seconds. If a delay cannot fit in the remaining budget or retries
|
|
70
|
+
are exhausted, the tool returns an explicit BookStack rate-limit error. The budget
|
|
71
|
+
applies to each API request; tools that fetch multiple endpoints can take longer.
|
|
72
|
+
|
|
73
|
+
With write operations enabled, `update_page` and `update_chapter` accept `priority`
|
|
74
|
+
as a non-negative integer (including numeric strings). Lower values sort first;
|
|
75
|
+
use these tools to order pages and chapters within a book.
|
|
76
|
+
|
|
77
|
+
`create_page` and `update_page` also accept an optional `changelog` message
|
|
78
|
+
(1–180 characters), saved as the revision summary in the page's history. It
|
|
79
|
+
needs BookStack v26.09 or newer; older versions silently ignore it.
|
|
80
|
+
|
|
60
81
|
> **Security warning:** `BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=true` disables TLS certificate verification for outgoing requests to BookStack. Use only for self-signed certs on a trusted LAN — connections become vulnerable to MITM attacks. The server logs a `WARNING` line at startup whenever this is enabled.
|
|
61
82
|
|
|
62
83
|
## Client Configuration
|
|
@@ -130,6 +151,48 @@ mcpServers:
|
|
|
130
151
|
url: http://bookstack-mcp:8080/mcp
|
|
131
152
|
```
|
|
132
153
|
|
|
154
|
+
#### Per-user BookStack credentials
|
|
155
|
+
|
|
156
|
+
Set `BOOKSTACK_ALLOW_REQUEST_CREDENTIALS=true` on the HTTP server to accept
|
|
157
|
+
`X-Bookstack-Token-Id` and `X-Bookstack-Token-Secret` on each request. Both headers
|
|
158
|
+
must be supplied together; when both are absent, the server uses its environment
|
|
159
|
+
credentials. This is opt-in and does not change the write-tool or OAuth role gates.
|
|
160
|
+
Use a read-only environment token with limited visibility for the fallback.
|
|
161
|
+
Credential overrides apply to each request, including reused MCP sessions, and
|
|
162
|
+
their slug caches are private to that request. Send credentials over HTTPS or a
|
|
163
|
+
trusted internal connection and configure proxies to redact these headers.
|
|
164
|
+
|
|
165
|
+
```yaml
|
|
166
|
+
mcpServers:
|
|
167
|
+
bookstack:
|
|
168
|
+
type: streamable-http
|
|
169
|
+
url: http://bookstack-mcp:8080/mcp
|
|
170
|
+
headers:
|
|
171
|
+
X-Bookstack-Token-Id: "{{BOOKSTACK_TOKEN_ID}}"
|
|
172
|
+
X-Bookstack-Token-Secret: "{{BOOKSTACK_TOKEN_SECRET}}"
|
|
173
|
+
customUserVars:
|
|
174
|
+
BOOKSTACK_TOKEN_ID: { title: "BookStack token ID" }
|
|
175
|
+
BOOKSTACK_TOKEN_SECRET: { title: "BookStack token secret" }
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
#### Gallery images
|
|
179
|
+
|
|
180
|
+
`list_images` lists images with optional `uploaded_to`, `offset`, `count`, and
|
|
181
|
+
`sort` parameters. With write mode enabled, `create_image` accepts exactly one
|
|
182
|
+
absolute `file_path` or HTTP(S) `url`, a required existing page ID `uploaded_to`,
|
|
183
|
+
and an optional `name`. It uploads the binary data directly and returns BookStack's
|
|
184
|
+
hosted URL, thumbnails, and `content.html` / `content.markdown` snippets. PNG,
|
|
185
|
+
JPEG, GIF, WebP, and SVG sources up to 50 MB are supported; BookStack may impose
|
|
186
|
+
smaller limits. `delete_image` deletes an image and its thumbnails by `id`.
|
|
187
|
+
|
|
188
|
+
In stdio mode, files and HTTP(S) URLs are available to the trusted local client.
|
|
189
|
+
In HTTP mode, local files are disabled unless
|
|
190
|
+
`BOOKSTACK_ALLOW_LOCAL_IMAGE_FILES=true`. URL sources require a comma-separated
|
|
191
|
+
`BOOKSTACK_IMAGE_ALLOWED_HOSTS` hostname allowlist, which also applies to every
|
|
192
|
+
redirect. For example, allow your image service with
|
|
193
|
+
`BOOKSTACK_IMAGE_ALLOWED_HOSTS=images.example.com`. Source downloads never use
|
|
194
|
+
the BookStack authorization token. Deleting an image can break existing page references.
|
|
195
|
+
|
|
133
196
|
> **3.0.0 breaking change:** the deprecated HTTP+SSE transport (`GET /sse` + `POST /messages`) has been removed. Streamable HTTP at `/mcp` already speaks SSE for streaming responses, and is the only HTTP transport in current MCP clients. If you're on an older client that needs the legacy endpoints, pin to `bookstack-mcp@2.x`.
|
|
134
197
|
|
|
135
198
|
#### HTTP transport environment variables
|
|
@@ -243,6 +306,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
243
306
|
| `get_chapters` / `get_chapter` | List or get chapter details |
|
|
244
307
|
| `get_shelves` / `get_shelf` | List or get shelf details |
|
|
245
308
|
| `get_attachments` / `get_attachment` | List or get attachment details |
|
|
309
|
+
| `list_images` | List gallery images, optionally filtered by page |
|
|
246
310
|
| `get_comments` / `get_comment` | List or get page comments (BookStack v25.11+) |
|
|
247
311
|
| `find_users` | Look up BookStack users by name, email, or slug to resolve user slugs for `{created_by:X}`-style search filters |
|
|
248
312
|
| `get_recycle_bin` | List items in the recycle bin |
|
|
@@ -262,6 +326,7 @@ Both templates support `id` autocompletion: as you type, the server searches Boo
|
|
|
262
326
|
| `delete_page` | Delete a page (recoverable from recycle bin) |
|
|
263
327
|
| `create_shelf` / `update_shelf` / `delete_shelf` | Manage shelves |
|
|
264
328
|
| `create_attachment` / `update_attachment` / `delete_attachment` | Manage attachments |
|
|
329
|
+
| `create_image` / `delete_image` | Upload gallery images from files or URLs, or delete images |
|
|
265
330
|
| `create_comment` / `update_comment` / `delete_comment` | Manage page comments (v25.11+) |
|
|
266
331
|
| `restore_deleted` / `permanently_delete` | Restore or permanently destroy items in the recycle bin |
|
|
267
332
|
|
package/dist/bookstack-client.js
CHANGED
|
@@ -2,18 +2,9 @@ import axios from 'axios';
|
|
|
2
2
|
import https from 'https';
|
|
3
3
|
import { Semaphore } from './util/semaphore.js';
|
|
4
4
|
import { countWords } from './util/word-count.js';
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
return null;
|
|
9
|
-
const seconds = Number(value);
|
|
10
|
-
if (Number.isFinite(seconds))
|
|
11
|
-
return Math.max(0, seconds * 1000);
|
|
12
|
-
const dateMs = Date.parse(value);
|
|
13
|
-
if (Number.isFinite(dateMs))
|
|
14
|
-
return Math.max(0, dateMs - Date.now());
|
|
15
|
-
return null;
|
|
16
|
-
}
|
|
5
|
+
import { rateLimitedAdapter } from './util/rate-limit.js';
|
|
6
|
+
import { MAX_IMAGE_BYTES, readImageSource } from './image-source.js';
|
|
7
|
+
import { PublicError, logSafeError, safeError } from './util/safe-errors.js';
|
|
17
8
|
// BookStack resolves {created_by:X}/{updated_by:X}/{owned_by:X} by user SLUG, with 'me'
|
|
18
9
|
// as a shortcut for the token's own user, and silently SKIPS the filter when X matches no
|
|
19
10
|
// user's slug — the query falls back to unfiltered results, which is a confusing footgun
|
|
@@ -25,7 +16,7 @@ function validateUserIdFilters(query) {
|
|
|
25
16
|
for (const match of query.matchAll(re)) {
|
|
26
17
|
const [, neg, field, value] = match;
|
|
27
18
|
if (/^\d+$/.test(value)) {
|
|
28
|
-
throw new
|
|
19
|
+
throw new PublicError(`Search filter {${neg}${field}:${value}} takes a user slug or 'me', not a numeric user ID — ` +
|
|
29
20
|
`BookStack resolves these filters by slug and silently returns unfiltered results for ` +
|
|
30
21
|
`unmatched values. Use the find_users tool to look up a user's slug by name or email.`);
|
|
31
22
|
}
|
|
@@ -68,9 +59,15 @@ export class BookStackClient {
|
|
|
68
59
|
client;
|
|
69
60
|
enableWrite;
|
|
70
61
|
baseUrl;
|
|
62
|
+
slugCache;
|
|
63
|
+
imageSourcePolicy;
|
|
71
64
|
constructor(config) {
|
|
72
65
|
this.enableWrite = config.enableWrite || false;
|
|
73
66
|
this.baseUrl = config.baseUrl;
|
|
67
|
+
this.imageSourcePolicy = config;
|
|
68
|
+
this.slugCache = config.privateSlugCache
|
|
69
|
+
? { cache: new Map(), inflight: new Map() }
|
|
70
|
+
: getSlugCacheEntry(config.baseUrl);
|
|
74
71
|
const limiter = getConcurrencyLimiter(config.baseUrl, config.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY);
|
|
75
72
|
const baseAdapter = axios.getAdapter(axios.defaults.adapter);
|
|
76
73
|
this.client = axios.create({
|
|
@@ -83,25 +80,11 @@ export class BookStackClient {
|
|
|
83
80
|
httpsAgent: config.insecureSkipTlsVerify
|
|
84
81
|
? new https.Agent({ rejectUnauthorized: false })
|
|
85
82
|
: undefined,
|
|
86
|
-
|
|
87
|
-
// this adapter exactly once per HTTP attempt. The retry's backoff sleep
|
|
88
|
-
// happens in the response interceptor (outside the adapter), so the
|
|
89
|
-
// permit is released between attempts, not held during the wait.
|
|
90
|
-
adapter: (requestConfig) => limiter.run(() => baseAdapter(requestConfig)),
|
|
83
|
+
adapter: rateLimitedAdapter(baseAdapter, limiter, config.retryTimeoutMs ?? 60000),
|
|
91
84
|
});
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
throw error;
|
|
96
|
-
cfg.__retry429 = (cfg.__retry429 ?? 0) + 1;
|
|
97
|
-
if (cfg.__retry429 > MAX_RETRIES_429)
|
|
98
|
-
throw error;
|
|
99
|
-
const retryAfter = parseRetryAfter(error.response.headers?.['retry-after']);
|
|
100
|
-
const backoff = Math.min(30000, 1000 * 2 ** (cfg.__retry429 - 1));
|
|
101
|
-
const delay = retryAfter ?? backoff;
|
|
102
|
-
console.error(`BookStack rate limited (429); retry ${cfg.__retry429}/${MAX_RETRIES_429} in ${delay}ms`);
|
|
103
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
104
|
-
return this.client.request(cfg);
|
|
85
|
+
// Do not let SDK error conversion or callers expose Axios config/bodies.
|
|
86
|
+
this.client.interceptors.response.use(undefined, error => {
|
|
87
|
+
throw safeError(error, 'BookStack request failed');
|
|
105
88
|
});
|
|
106
89
|
}
|
|
107
90
|
applyFilters(params, filter) {
|
|
@@ -125,7 +108,7 @@ export class BookStackClient {
|
|
|
125
108
|
* single in-flight warm. Failure is non-fatal: getBookSlug lazily fills gaps.
|
|
126
109
|
*/
|
|
127
110
|
async warmBookSlugCache() {
|
|
128
|
-
const entry =
|
|
111
|
+
const entry = this.slugCache;
|
|
129
112
|
// A completed warm is still fresh → nothing to do (lazy fetch covers gaps).
|
|
130
113
|
if (entry.warmedAt !== undefined && Date.now() - entry.warmedAt < SLUG_CACHE_TTL_MS) {
|
|
131
114
|
return;
|
|
@@ -167,7 +150,7 @@ export class BookStackClient {
|
|
|
167
150
|
// A single bulk warm turns the per-result N+1 into +1; after it, every book
|
|
168
151
|
// that existed at warm time is a cache hit — shared across all sessions.
|
|
169
152
|
await this.warmBookSlugCache();
|
|
170
|
-
const entry =
|
|
153
|
+
const entry = this.slugCache;
|
|
171
154
|
const cached = entry.cache.get(bookId);
|
|
172
155
|
if (cached !== undefined)
|
|
173
156
|
return cached;
|
|
@@ -413,7 +396,7 @@ export class BookStackClient {
|
|
|
413
396
|
}
|
|
414
397
|
}
|
|
415
398
|
catch (error) {
|
|
416
|
-
|
|
399
|
+
logSafeError(`Markdown export fallback failed for page ${id}`, error);
|
|
417
400
|
}
|
|
418
401
|
}
|
|
419
402
|
return await this.enhancePageResponse(pageData, options);
|
|
@@ -433,65 +416,105 @@ export class BookStackClient {
|
|
|
433
416
|
const response = await this.client.get(`/chapters/${id}`);
|
|
434
417
|
return await this.enhanceChapterResponse(response.data);
|
|
435
418
|
}
|
|
419
|
+
async listImages(options = {}) {
|
|
420
|
+
const params = { offset: options.offset ?? 0, count: Math.min(options.count ?? 50, 500) };
|
|
421
|
+
if (options.sort)
|
|
422
|
+
params.sort = options.sort;
|
|
423
|
+
if (options.uploaded_to !== undefined)
|
|
424
|
+
params['filter[uploaded_to]'] = options.uploaded_to;
|
|
425
|
+
return (await this.client.get('/image-gallery', { params })).data;
|
|
426
|
+
}
|
|
427
|
+
async createImage(data) {
|
|
428
|
+
if (!this.enableWrite)
|
|
429
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
430
|
+
if (!Number.isInteger(data.uploaded_to) || data.uploaded_to < 1)
|
|
431
|
+
throw new PublicError('uploaded_to must be a positive page ID.');
|
|
432
|
+
const source = await readImageSource({ ...data,
|
|
433
|
+
allowLocalFiles: this.imageSourcePolicy.allowLocalImageFiles,
|
|
434
|
+
allowedHosts: this.imageSourcePolicy.imageAllowedHosts
|
|
435
|
+
});
|
|
436
|
+
const form = new FormData();
|
|
437
|
+
form.set('type', 'gallery');
|
|
438
|
+
form.set('uploaded_to', String(data.uploaded_to));
|
|
439
|
+
if (data.name !== undefined)
|
|
440
|
+
form.set('name', data.name);
|
|
441
|
+
form.set('image', new Blob([new Uint8Array(source.bytes)], { type: source.type }), source.filename);
|
|
442
|
+
try {
|
|
443
|
+
// Removing the JSON default lets Axios set the multipart boundary. Using
|
|
444
|
+
// the existing client preserves token auth, TLS settings and retry limits.
|
|
445
|
+
return (await this.client.post('/image-gallery', form, {
|
|
446
|
+
headers: { 'Content-Type': undefined }, maxBodyLength: MAX_IMAGE_BYTES + 1024 * 1024
|
|
447
|
+
})).data;
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
throw safeError(error, 'BookStack image upload failed');
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
async deleteImage(id) {
|
|
454
|
+
if (!this.enableWrite)
|
|
455
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
456
|
+
await this.client.delete(`/image-gallery/${id}`);
|
|
457
|
+
return { deleted: true, id };
|
|
458
|
+
}
|
|
436
459
|
async createBook(data) {
|
|
437
460
|
if (!this.enableWrite) {
|
|
438
|
-
throw new
|
|
461
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
439
462
|
}
|
|
440
463
|
const response = await this.client.post('/books', data);
|
|
441
464
|
return this.enhanceBookResponse(response.data);
|
|
442
465
|
}
|
|
443
466
|
async createChapter(data) {
|
|
444
467
|
if (!this.enableWrite) {
|
|
445
|
-
throw new
|
|
468
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
446
469
|
}
|
|
447
470
|
const response = await this.client.post('/chapters', data);
|
|
448
471
|
return await this.enhanceChapterResponse(response.data);
|
|
449
472
|
}
|
|
450
473
|
async updateBook(id, data) {
|
|
451
474
|
if (!this.enableWrite) {
|
|
452
|
-
throw new
|
|
475
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
453
476
|
}
|
|
454
477
|
const response = await this.client.put(`/books/${id}`, data);
|
|
455
478
|
return this.enhanceBookResponse(response.data);
|
|
456
479
|
}
|
|
457
480
|
async updateChapter(id, data) {
|
|
458
481
|
if (!this.enableWrite) {
|
|
459
|
-
throw new
|
|
482
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
460
483
|
}
|
|
461
484
|
const response = await this.client.put(`/chapters/${id}`, data);
|
|
462
485
|
return await this.enhanceChapterResponse(response.data);
|
|
463
486
|
}
|
|
464
487
|
async createPage(data) {
|
|
465
488
|
if (!this.enableWrite) {
|
|
466
|
-
throw new
|
|
489
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
467
490
|
}
|
|
468
491
|
const response = await this.client.post('/pages', data);
|
|
469
492
|
return await this.enhancePageResponse(response.data);
|
|
470
493
|
}
|
|
471
494
|
async deleteBook(id) {
|
|
472
495
|
if (!this.enableWrite) {
|
|
473
|
-
throw new
|
|
496
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
474
497
|
}
|
|
475
498
|
const response = await this.client.delete(`/books/${id}`);
|
|
476
499
|
return response.data;
|
|
477
500
|
}
|
|
478
501
|
async deleteChapter(id) {
|
|
479
502
|
if (!this.enableWrite) {
|
|
480
|
-
throw new
|
|
503
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
481
504
|
}
|
|
482
505
|
const response = await this.client.delete(`/chapters/${id}`);
|
|
483
506
|
return response.data;
|
|
484
507
|
}
|
|
485
508
|
async deletePage(id) {
|
|
486
509
|
if (!this.enableWrite) {
|
|
487
|
-
throw new
|
|
510
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
488
511
|
}
|
|
489
512
|
const response = await this.client.delete(`/pages/${id}`);
|
|
490
513
|
return response.data;
|
|
491
514
|
}
|
|
492
515
|
async updatePage(id, data) {
|
|
493
516
|
if (!this.enableWrite) {
|
|
494
|
-
throw new
|
|
517
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
495
518
|
}
|
|
496
519
|
const response = await this.client.put(`/pages/${id}`, data);
|
|
497
520
|
return await this.enhancePageResponse(response.data);
|
|
@@ -527,15 +550,15 @@ export class BookStackClient {
|
|
|
527
550
|
console.error(`Export response status: ${response.status}`);
|
|
528
551
|
// For text formats, validate and return as string
|
|
529
552
|
if (!response.data) {
|
|
530
|
-
throw new
|
|
553
|
+
throw new PublicError(`Empty ${format} content returned from BookStack API`);
|
|
531
554
|
}
|
|
532
555
|
console.error(`Text export length: ${response.data.length} characters`);
|
|
533
556
|
return response.data;
|
|
534
557
|
}
|
|
535
558
|
}
|
|
536
559
|
catch (error) {
|
|
537
|
-
|
|
538
|
-
throw
|
|
560
|
+
logSafeError(`Export error for page ${id}`, error);
|
|
561
|
+
throw safeError(error, `Failed to export page ${id} as ${format}`);
|
|
539
562
|
}
|
|
540
563
|
}
|
|
541
564
|
async exportBook(id, format) {
|
|
@@ -659,21 +682,21 @@ export class BookStackClient {
|
|
|
659
682
|
}
|
|
660
683
|
async createShelf(data) {
|
|
661
684
|
if (!this.enableWrite) {
|
|
662
|
-
throw new
|
|
685
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
663
686
|
}
|
|
664
687
|
const response = await this.client.post('/shelves', data);
|
|
665
688
|
return this.enhanceShelfResponse(response.data);
|
|
666
689
|
}
|
|
667
690
|
async updateShelf(id, data) {
|
|
668
691
|
if (!this.enableWrite) {
|
|
669
|
-
throw new
|
|
692
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
670
693
|
}
|
|
671
694
|
const response = await this.client.put(`/shelves/${id}`, data);
|
|
672
695
|
return this.enhanceShelfResponse(response.data);
|
|
673
696
|
}
|
|
674
697
|
async deleteShelf(id) {
|
|
675
698
|
if (!this.enableWrite) {
|
|
676
|
-
throw new
|
|
699
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
677
700
|
}
|
|
678
701
|
const response = await this.client.delete(`/shelves/${id}`);
|
|
679
702
|
return response.data;
|
|
@@ -707,7 +730,7 @@ export class BookStackClient {
|
|
|
707
730
|
}
|
|
708
731
|
async createAttachment(data) {
|
|
709
732
|
if (!this.enableWrite) {
|
|
710
|
-
throw new
|
|
733
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
711
734
|
}
|
|
712
735
|
const response = await this.client.post('/attachments', data);
|
|
713
736
|
const attachment = response.data;
|
|
@@ -718,7 +741,7 @@ export class BookStackClient {
|
|
|
718
741
|
}
|
|
719
742
|
async updateAttachment(id, data) {
|
|
720
743
|
if (!this.enableWrite) {
|
|
721
|
-
throw new
|
|
744
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
722
745
|
}
|
|
723
746
|
const response = await this.client.put(`/attachments/${id}`, data);
|
|
724
747
|
const attachment = response.data;
|
|
@@ -729,7 +752,7 @@ export class BookStackClient {
|
|
|
729
752
|
}
|
|
730
753
|
async deleteAttachment(id) {
|
|
731
754
|
if (!this.enableWrite) {
|
|
732
|
-
throw new
|
|
755
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
733
756
|
}
|
|
734
757
|
const response = await this.client.delete(`/attachments/${id}`);
|
|
735
758
|
return response.data;
|
|
@@ -753,21 +776,21 @@ export class BookStackClient {
|
|
|
753
776
|
}
|
|
754
777
|
async createComment(data) {
|
|
755
778
|
if (!this.enableWrite) {
|
|
756
|
-
throw new
|
|
779
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
757
780
|
}
|
|
758
781
|
const response = await this.client.post('/comments', data);
|
|
759
782
|
return response.data;
|
|
760
783
|
}
|
|
761
784
|
async updateComment(id, data) {
|
|
762
785
|
if (!this.enableWrite) {
|
|
763
|
-
throw new
|
|
786
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
764
787
|
}
|
|
765
788
|
const response = await this.client.put(`/comments/${id}`, data);
|
|
766
789
|
return response.data;
|
|
767
790
|
}
|
|
768
791
|
async deleteComment(id) {
|
|
769
792
|
if (!this.enableWrite) {
|
|
770
|
-
throw new
|
|
793
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
771
794
|
}
|
|
772
795
|
const response = await this.client.delete(`/comments/${id}`);
|
|
773
796
|
return response.data;
|
|
@@ -785,14 +808,14 @@ export class BookStackClient {
|
|
|
785
808
|
}
|
|
786
809
|
async restoreFromRecycleBin(deletionId) {
|
|
787
810
|
if (!this.enableWrite) {
|
|
788
|
-
throw new
|
|
811
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
789
812
|
}
|
|
790
813
|
const response = await this.client.put(`/recycle-bin/${deletionId}`);
|
|
791
814
|
return response.data;
|
|
792
815
|
}
|
|
793
816
|
async destroyFromRecycleBin(deletionId) {
|
|
794
817
|
if (!this.enableWrite) {
|
|
795
|
-
throw new
|
|
818
|
+
throw new PublicError('Write operations are disabled. Set BOOKSTACK_ENABLE_WRITE=true to enable.');
|
|
796
819
|
}
|
|
797
820
|
const response = await this.client.delete(`/recycle-bin/${deletionId}`);
|
|
798
821
|
return response.data;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import { open } from 'node:fs/promises';
|
|
3
|
+
import { basename, extname, isAbsolute } from 'node:path';
|
|
4
|
+
import { PublicError, safeError } from './util/safe-errors.js';
|
|
5
|
+
export const MAX_IMAGE_BYTES = 50 * 1024 * 1024;
|
|
6
|
+
const TYPES = {
|
|
7
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
8
|
+
'.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml'
|
|
9
|
+
};
|
|
10
|
+
export async function readImageSource(options) {
|
|
11
|
+
try {
|
|
12
|
+
return await loadImageSource(options);
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
throw safeError(error, 'Image source read failed');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function loadImageSource(options) {
|
|
19
|
+
if (!!options.file_path === !!options.url)
|
|
20
|
+
throw new PublicError('Provide exactly one of file_path or url.');
|
|
21
|
+
let bytes;
|
|
22
|
+
let filename;
|
|
23
|
+
let type;
|
|
24
|
+
if (options.file_path) {
|
|
25
|
+
if (options.allowLocalFiles === false)
|
|
26
|
+
throw new PublicError('Local image files are disabled for this server.');
|
|
27
|
+
if (!isAbsolute(options.file_path))
|
|
28
|
+
throw new PublicError('file_path must be absolute.');
|
|
29
|
+
filename = basename(options.file_path);
|
|
30
|
+
type = TYPES[extname(filename).toLowerCase()];
|
|
31
|
+
if (!type)
|
|
32
|
+
throw new PublicError('Supported image formats: PNG, JPEG, GIF, WebP and SVG.');
|
|
33
|
+
const file = await open(options.file_path, 'r');
|
|
34
|
+
try {
|
|
35
|
+
const stat = await file.stat();
|
|
36
|
+
if (!stat.isFile() || stat.size > MAX_IMAGE_BYTES)
|
|
37
|
+
throw new PublicError('Image must be a regular file no larger than 50 MB.');
|
|
38
|
+
bytes = Buffer.alloc(stat.size);
|
|
39
|
+
let offset = 0;
|
|
40
|
+
while (offset < bytes.length) {
|
|
41
|
+
const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
|
|
42
|
+
if (!bytesRead)
|
|
43
|
+
break;
|
|
44
|
+
offset += bytesRead;
|
|
45
|
+
}
|
|
46
|
+
bytes = bytes.subarray(0, offset);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await file.close();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
let url = new URL(options.url);
|
|
54
|
+
for (let redirect = 0;; redirect++) {
|
|
55
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
|
|
56
|
+
throw new PublicError('Image URL must use HTTP(S) without embedded credentials.');
|
|
57
|
+
}
|
|
58
|
+
if (options.allowedHosts && !options.allowedHosts.includes(url.hostname.toLowerCase())) {
|
|
59
|
+
throw new PublicError('Image URL host is not in BOOKSTACK_IMAGE_ALLOWED_HOSTS.');
|
|
60
|
+
}
|
|
61
|
+
const response = await axios.get(url.href, {
|
|
62
|
+
responseType: 'arraybuffer', maxContentLength: MAX_IMAGE_BYTES,
|
|
63
|
+
maxRedirects: 0, timeout: 30000,
|
|
64
|
+
validateStatus: status => (status >= 200 && status < 300) || [301, 302, 303, 307, 308].includes(status)
|
|
65
|
+
});
|
|
66
|
+
if (response.status >= 300) {
|
|
67
|
+
if (redirect >= 3 || !response.headers.location)
|
|
68
|
+
throw new PublicError('Too many image URL redirects or missing Location.');
|
|
69
|
+
url = new URL(response.headers.location, url);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
filename = basename(url.pathname) || 'image';
|
|
73
|
+
type = String(response.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
|
|
74
|
+
if (!Object.values(TYPES).includes(type))
|
|
75
|
+
type = TYPES[extname(filename).toLowerCase()];
|
|
76
|
+
if (!type)
|
|
77
|
+
throw new PublicError('Supported image formats: PNG, JPEG, GIF, WebP and SVG.');
|
|
78
|
+
bytes = Buffer.from(response.data);
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!bytes.length || bytes.length > MAX_IMAGE_BYTES)
|
|
83
|
+
throw new PublicError('Image must contain between 1 byte and 50 MB.');
|
|
84
|
+
return { bytes, filename, type };
|
|
85
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -9,10 +9,11 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
9
9
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
10
10
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
11
11
|
import { z } from "zod";
|
|
12
|
-
import { BookStackClient } from "./bookstack-client.js";
|
|
13
12
|
import { registerPrompts } from "./prompts.js";
|
|
14
13
|
import { loadOAuthConfig, initOAuthStore, handleOAuthRoutes, validateBearer, sendUnauthorized } from "./oauth/entra-proxy.js";
|
|
15
14
|
import { SessionRegistry } from "./session-registry.js";
|
|
15
|
+
import { parseRequestCredentials, requestScopedClient, withRequestCredentials } from "./request-credentials.js";
|
|
16
|
+
import { PublicError, logSafeError, safeError, safeUrlOrigin } from "./util/safe-errors.js";
|
|
16
17
|
const PKG_VERSION = (() => {
|
|
17
18
|
try {
|
|
18
19
|
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
@@ -41,7 +42,7 @@ function getRequiredEnvVar(name) {
|
|
|
41
42
|
return value;
|
|
42
43
|
}
|
|
43
44
|
function buildServer(config) {
|
|
44
|
-
const client =
|
|
45
|
+
const client = requestScopedClient(config);
|
|
45
46
|
const server = new McpServer({
|
|
46
47
|
name: "bookstack-mcp",
|
|
47
48
|
version: PKG_VERSION
|
|
@@ -79,7 +80,7 @@ function registerResources(server, client) {
|
|
|
79
80
|
}, async (uri, variables) => {
|
|
80
81
|
const id = Number(variables.id);
|
|
81
82
|
if (!Number.isFinite(id) || id < 1) {
|
|
82
|
-
throw new
|
|
83
|
+
throw new PublicError(`Invalid book id: ${variables.id}`);
|
|
83
84
|
}
|
|
84
85
|
const book = await client.getBook(id);
|
|
85
86
|
return {
|
|
@@ -117,7 +118,7 @@ function registerResources(server, client) {
|
|
|
117
118
|
}, async (uri, variables) => {
|
|
118
119
|
const id = Number(variables.id);
|
|
119
120
|
if (!Number.isFinite(id) || id < 1) {
|
|
120
|
-
throw new
|
|
121
|
+
throw new PublicError(`Invalid page id: ${variables.id}`);
|
|
121
122
|
}
|
|
122
123
|
const page = await client.getPage(id, { format: "markdown" });
|
|
123
124
|
return {
|
|
@@ -144,11 +145,19 @@ function registerResources(server, client) {
|
|
|
144
145
|
});
|
|
145
146
|
}
|
|
146
147
|
function registerTools(server, client, config) {
|
|
148
|
+
const safeHandler = (handler) => async (...args) => {
|
|
149
|
+
try {
|
|
150
|
+
return await handler(...args);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
throw safeError(error);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
147
156
|
// Helpers wrap registerTool and inject MCP tool annotations so clients can
|
|
148
157
|
// distinguish read-only from destructive operations. Typed loosely to defer
|
|
149
158
|
// to the SDK's generic overloads at the call sites.
|
|
150
|
-
const readTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...READ_ONLY_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
|
|
151
|
-
const writeTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...WRITE_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, handler));
|
|
159
|
+
const readTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...READ_ONLY_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, safeHandler(handler)));
|
|
160
|
+
const writeTool = ((name, cfg, handler) => server.registerTool(name, { ...cfg, annotations: { ...WRITE_ANNOTATIONS, ...(cfg.annotations ?? {}) } }, safeHandler(handler)));
|
|
152
161
|
// Register read-only tools.
|
|
153
162
|
// Common params (offset/count/sort/filter/id) are self-describing and intentionally
|
|
154
163
|
// bare so tool definitions stay compact in the MCP tools/list payload.
|
|
@@ -190,7 +199,7 @@ function registerTools(server, client, config) {
|
|
|
190
199
|
offset: z.coerce.number().default(0),
|
|
191
200
|
count: z.coerce.number().max(500).default(50),
|
|
192
201
|
sort: z.string().optional(),
|
|
193
|
-
filter: z.record(z.any()).optional()
|
|
202
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
194
203
|
}
|
|
195
204
|
}, async (args) => {
|
|
196
205
|
const books = await client.getBooks({
|
|
@@ -222,7 +231,7 @@ function registerTools(server, client, config) {
|
|
|
222
231
|
offset: z.coerce.number().default(0),
|
|
223
232
|
count: z.coerce.number().max(500).default(50),
|
|
224
233
|
sort: z.string().optional(),
|
|
225
|
-
filter: z.record(z.any()).optional()
|
|
234
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
226
235
|
}
|
|
227
236
|
}, async (args) => {
|
|
228
237
|
const pages = await client.getPages({
|
|
@@ -350,7 +359,7 @@ function registerTools(server, client, config) {
|
|
|
350
359
|
offset: z.coerce.number().default(0),
|
|
351
360
|
count: z.coerce.number().max(500).default(50),
|
|
352
361
|
sort: z.string().optional(),
|
|
353
|
-
filter: z.record(z.any()).optional()
|
|
362
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
354
363
|
}
|
|
355
364
|
}, async (args) => {
|
|
356
365
|
const shelves = await client.getShelves({
|
|
@@ -380,7 +389,7 @@ function registerTools(server, client, config) {
|
|
|
380
389
|
offset: z.coerce.number().default(0),
|
|
381
390
|
count: z.coerce.number().max(500).default(50),
|
|
382
391
|
sort: z.string().optional(),
|
|
383
|
-
filter: z.record(z.any()).optional()
|
|
392
|
+
filter: z.record(z.string(), z.any()).optional()
|
|
384
393
|
}
|
|
385
394
|
}, async (args) => {
|
|
386
395
|
const attachments = await client.getAttachments({
|
|
@@ -479,8 +488,30 @@ function registerTools(server, client, config) {
|
|
|
479
488
|
content: [{ type: "text", text: JSON.stringify(items) }]
|
|
480
489
|
};
|
|
481
490
|
});
|
|
491
|
+
readTool("list_images", {
|
|
492
|
+
description: "List gallery images, optionally filtered by their page ID.",
|
|
493
|
+
inputSchema: {
|
|
494
|
+
uploaded_to: z.coerce.number().int().min(1).optional(),
|
|
495
|
+
offset: z.coerce.number().int().min(0).optional(),
|
|
496
|
+
count: z.coerce.number().int().min(1).max(500).optional(),
|
|
497
|
+
sort: z.string().optional()
|
|
498
|
+
}
|
|
499
|
+
}, async (args) => ({ content: [{ type: "text", text: JSON.stringify(await client.listImages(args)) }] }));
|
|
482
500
|
// Register write tools if enabled
|
|
483
501
|
if (config.enableWrite) {
|
|
502
|
+
writeTool("create_image", {
|
|
503
|
+
description: "Upload a gallery image from exactly one absolute file_path or HTTP(S) url. Server source policy applies. Returns hosted URL, thumbnails and HTML/Markdown content.",
|
|
504
|
+
inputSchema: {
|
|
505
|
+
file_path: z.string().min(1).optional(),
|
|
506
|
+
url: z.string().url().optional(),
|
|
507
|
+
name: z.string().min(1).max(180).optional(),
|
|
508
|
+
uploaded_to: z.coerce.number().int().min(1).describe("Existing page ID")
|
|
509
|
+
}
|
|
510
|
+
}, async (args) => ({ content: [{ type: "text", text: JSON.stringify(await client.createImage(args)) }] }));
|
|
511
|
+
writeTool("delete_image", {
|
|
512
|
+
description: "Delete a gallery image and its thumbnails. Existing page references may break.",
|
|
513
|
+
inputSchema: { id: z.coerce.number().int().min(1) }
|
|
514
|
+
}, async (args) => ({ content: [{ type: "text", text: JSON.stringify(await client.deleteImage(args.id)) }] }));
|
|
484
515
|
writeTool("create_book", {
|
|
485
516
|
description: "Create a new book in BookStack",
|
|
486
517
|
inputSchema: {
|
|
@@ -576,7 +607,8 @@ function registerTools(server, client, config) {
|
|
|
576
607
|
book_id: z.coerce.number().min(1).describe("Book ID where the page will be created"),
|
|
577
608
|
chapter_id: z.coerce.number().optional().describe("Optional: Chapter ID if page should be in a chapter"),
|
|
578
609
|
html: z.string().optional().describe("Optional: HTML content"),
|
|
579
|
-
markdown: z.string().optional().describe("Optional: Markdown content")
|
|
610
|
+
markdown: z.string().optional().describe("Optional: Markdown content"),
|
|
611
|
+
changelog: z.string().min(1).max(180).optional().describe("Optional: Revision changelog message shown in the page history (BookStack v26.09+; older servers ignore it)")
|
|
580
612
|
}
|
|
581
613
|
}, async (args) => {
|
|
582
614
|
const page = await client.createPage({
|
|
@@ -584,21 +616,24 @@ function registerTools(server, client, config) {
|
|
|
584
616
|
book_id: args.book_id,
|
|
585
617
|
chapter_id: args.chapter_id,
|
|
586
618
|
html: args.html,
|
|
587
|
-
markdown: args.markdown
|
|
619
|
+
markdown: args.markdown,
|
|
620
|
+
changelog: args.changelog
|
|
588
621
|
});
|
|
589
622
|
return {
|
|
590
623
|
content: [{ type: "text", text: JSON.stringify(page) }]
|
|
591
624
|
};
|
|
592
625
|
});
|
|
593
626
|
writeTool("update_page", {
|
|
594
|
-
description: "Update an existing page. Pass book_id (and optionally chapter_id) to move the page to a different location.",
|
|
627
|
+
description: "Update an existing page. Pass book_id (and optionally chapter_id) to move the page to a different location, or priority to reorder it.",
|
|
595
628
|
inputSchema: {
|
|
596
629
|
id: z.coerce.number().min(1),
|
|
597
630
|
name: z.string().optional().describe("Optional: New page name"),
|
|
598
631
|
html: z.string().optional().describe("Optional: New HTML content"),
|
|
599
632
|
markdown: z.string().optional().describe("Optional: New Markdown content"),
|
|
600
633
|
book_id: z.coerce.number().min(1).optional().describe("Optional: Move page to this book"),
|
|
601
|
-
chapter_id: z.coerce.number().optional().describe("Optional: Move page into this chapter (must belong to the target book; pass 0 to move out of any chapter)")
|
|
634
|
+
chapter_id: z.coerce.number().optional().describe("Optional: Move page into this chapter (must belong to the target book; pass 0 to move out of any chapter)"),
|
|
635
|
+
priority: z.coerce.number().int().min(0).optional().describe("Optional: Sort order (non-negative integer, lower sorts first)"),
|
|
636
|
+
changelog: z.string().min(1).max(180).optional().describe("Optional: Revision changelog message shown in the page history (BookStack v26.09+; older servers ignore it)")
|
|
602
637
|
}
|
|
603
638
|
}, async (args) => {
|
|
604
639
|
const page = await client.updatePage(args.id, {
|
|
@@ -606,7 +641,9 @@ function registerTools(server, client, config) {
|
|
|
606
641
|
html: args.html,
|
|
607
642
|
markdown: args.markdown,
|
|
608
643
|
book_id: args.book_id,
|
|
609
|
-
chapter_id: args.chapter_id
|
|
644
|
+
chapter_id: args.chapter_id,
|
|
645
|
+
priority: args.priority,
|
|
646
|
+
changelog: args.changelog
|
|
610
647
|
});
|
|
611
648
|
return {
|
|
612
649
|
content: [{ type: "text", text: JSON.stringify(page) }]
|
|
@@ -824,6 +861,7 @@ async function startStdio(config) {
|
|
|
824
861
|
console.error("BookStack MCP server running on stdio");
|
|
825
862
|
}
|
|
826
863
|
async function startHttp(config) {
|
|
864
|
+
const requestCredentialsEnabled = process.env.BOOKSTACK_ALLOW_REQUEST_CREDENTIALS?.toLowerCase() === "true";
|
|
827
865
|
const port = parseInt(process.env.MCP_HTTP_PORT ?? "8080", 10);
|
|
828
866
|
const host = process.env.MCP_HTTP_HOST ?? "127.0.0.1";
|
|
829
867
|
const mcpPath = process.env.MCP_HTTP_PATH ?? "/mcp";
|
|
@@ -903,6 +941,14 @@ async function startHttp(config) {
|
|
|
903
941
|
}
|
|
904
942
|
auth = { sub: result.sub, isWriter: !!result.isWriter };
|
|
905
943
|
}
|
|
944
|
+
let requestCredentials;
|
|
945
|
+
try {
|
|
946
|
+
requestCredentials = parseRequestCredentials(req.headers, requestCredentialsEnabled);
|
|
947
|
+
}
|
|
948
|
+
catch (error) {
|
|
949
|
+
sendJson(res, 400, { jsonrpc: "2.0", error: { code: -32602, message: error.message }, id: null });
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
906
952
|
const sessionId = req.headers["mcp-session-id"];
|
|
907
953
|
let transport;
|
|
908
954
|
let parsedBody;
|
|
@@ -975,7 +1021,7 @@ async function startHttp(config) {
|
|
|
975
1021
|
});
|
|
976
1022
|
return;
|
|
977
1023
|
}
|
|
978
|
-
await transport.handleRequest(req, res, parsedBody);
|
|
1024
|
+
await withRequestCredentials(requestCredentials, () => transport.handleRequest(req, res, parsedBody));
|
|
979
1025
|
return;
|
|
980
1026
|
}
|
|
981
1027
|
// Health check
|
|
@@ -992,7 +1038,7 @@ async function startHttp(config) {
|
|
|
992
1038
|
sendJson(res, 404, { error: "Not Found" });
|
|
993
1039
|
}
|
|
994
1040
|
catch (err) {
|
|
995
|
-
|
|
1041
|
+
logSafeError("HTTP handler error", err);
|
|
996
1042
|
if (!res.headersSent) {
|
|
997
1043
|
sendJson(res, 500, {
|
|
998
1044
|
jsonrpc: "2.0",
|
|
@@ -1027,11 +1073,16 @@ async function startHttp(config) {
|
|
|
1027
1073
|
}
|
|
1028
1074
|
async function main() {
|
|
1029
1075
|
const baseUrl = getRequiredEnvVar('BOOKSTACK_BASE_URL');
|
|
1076
|
+
const transportMode = (process.env.MCP_TRANSPORT ?? 'stdio').toLowerCase();
|
|
1077
|
+
const isHttpTransport = transportMode === 'http' || transportMode === 'sse';
|
|
1030
1078
|
const insecureSkipTlsVerify = process.env.BOOKSTACK_INSECURE_SKIP_TLS_VERIFY?.toLowerCase() === 'true';
|
|
1031
1079
|
const envEnableWrite = process.env.BOOKSTACK_ENABLE_WRITE?.toLowerCase() === 'true';
|
|
1032
1080
|
const timeoutRaw = process.env.BOOKSTACK_TIMEOUT_MS;
|
|
1033
1081
|
const timeoutParsed = timeoutRaw ? parseInt(timeoutRaw, 10) : NaN;
|
|
1034
1082
|
const timeoutMs = Number.isFinite(timeoutParsed) && timeoutParsed > 0 ? timeoutParsed : undefined;
|
|
1083
|
+
const retryTimeoutParsed = Number(process.env.BOOKSTACK_RETRY_TIMEOUT_MS);
|
|
1084
|
+
const retryTimeoutMs = Number.isFinite(retryTimeoutParsed) && retryTimeoutParsed > 0
|
|
1085
|
+
? retryTimeoutParsed : undefined;
|
|
1035
1086
|
const concurrencyRaw = process.env.BOOKSTACK_MAX_CONCURRENCY;
|
|
1036
1087
|
const concurrencyParsed = concurrencyRaw ? parseInt(concurrencyRaw, 10) : NaN;
|
|
1037
1088
|
const maxConcurrency = Number.isFinite(concurrencyParsed) && concurrencyParsed > 0
|
|
@@ -1053,6 +1104,11 @@ async function main() {
|
|
|
1053
1104
|
enableWrite: oauth ? false : envEnableWrite,
|
|
1054
1105
|
insecureSkipTlsVerify,
|
|
1055
1106
|
timeoutMs,
|
|
1107
|
+
retryTimeoutMs,
|
|
1108
|
+
allowLocalImageFiles: !isHttpTransport || process.env.BOOKSTACK_ALLOW_LOCAL_IMAGE_FILES?.toLowerCase() === 'true',
|
|
1109
|
+
imageAllowedHosts: isHttpTransport
|
|
1110
|
+
? (process.env.BOOKSTACK_IMAGE_ALLOWED_HOSTS ?? '').split(',').map(host => host.trim().toLowerCase()).filter(Boolean)
|
|
1111
|
+
: undefined,
|
|
1056
1112
|
maxConcurrency
|
|
1057
1113
|
};
|
|
1058
1114
|
// The write credential is optional and only used by the OAuth proxy for sessions whose
|
|
@@ -1060,14 +1116,14 @@ async function main() {
|
|
|
1060
1116
|
const writeTokenId = process.env.BOOKSTACK_WRITE_TOKEN_ID;
|
|
1061
1117
|
const writeTokenSecret = process.env.BOOKSTACK_WRITE_TOKEN_SECRET;
|
|
1062
1118
|
const write = (writeTokenId && writeTokenSecret)
|
|
1063
|
-
? {
|
|
1119
|
+
? { ...read, tokenId: writeTokenId, tokenSecret: writeTokenSecret, enableWrite: true }
|
|
1064
1120
|
: null;
|
|
1065
1121
|
const config = { read, write, oauth };
|
|
1066
1122
|
console.error('Initializing BookStack MCP Server...');
|
|
1067
|
-
console.error(`BookStack
|
|
1123
|
+
console.error(`BookStack origin: ${safeUrlOrigin(baseUrl)}`);
|
|
1068
1124
|
if (oauth) {
|
|
1069
1125
|
console.error(`Auth: Entra OAuth proxy ENABLED (tenant ${oauth.tenantId})`);
|
|
1070
|
-
console.error(` Public
|
|
1126
|
+
console.error(` Public origin: ${safeUrlOrigin(oauth.serverUrl)}`);
|
|
1071
1127
|
console.error(` Write role: ${oauth.writeRole}`);
|
|
1072
1128
|
if (!write) {
|
|
1073
1129
|
console.error(' WARNING: no BOOKSTACK_WRITE_TOKEN_ID/SECRET set — all sessions are read-only regardless of role.');
|
|
@@ -1079,8 +1135,7 @@ async function main() {
|
|
|
1079
1135
|
if (insecureSkipTlsVerify) {
|
|
1080
1136
|
console.error('WARNING: TLS certificate verification is DISABLED (BOOKSTACK_INSECURE_SKIP_TLS_VERIFY=true). Connections to BookStack are vulnerable to MITM attacks. Use only with trusted self-signed certs on a trusted network.');
|
|
1081
1137
|
}
|
|
1082
|
-
|
|
1083
|
-
if (transportMode === "http" || transportMode === "sse") {
|
|
1138
|
+
if (isHttpTransport) {
|
|
1084
1139
|
await startHttp(config);
|
|
1085
1140
|
}
|
|
1086
1141
|
else {
|
|
@@ -1088,6 +1143,6 @@ async function main() {
|
|
|
1088
1143
|
}
|
|
1089
1144
|
}
|
|
1090
1145
|
main().catch((err) => {
|
|
1091
|
-
|
|
1146
|
+
logSafeError('Server startup failed', err);
|
|
1092
1147
|
process.exit(1);
|
|
1093
1148
|
});
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { randomUUID, createHash, randomBytes } from "node:crypto";
|
|
13
13
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
14
14
|
import { InMemoryKvStore, createStore } from "./kv-store.js";
|
|
15
|
+
import { logSafeError, oauthErrorCode } from "../util/safe-errors.js";
|
|
15
16
|
// Load config from env. Returns null when OAuth proxy mode is disabled.
|
|
16
17
|
export function loadOAuthConfig(env) {
|
|
17
18
|
if (env.MCP_OAUTH_ENABLE?.toLowerCase() !== "true")
|
|
@@ -162,9 +163,9 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
162
163
|
const url = new URL(req.url ?? "/", cfg.serverUrl);
|
|
163
164
|
const path = url.pathname;
|
|
164
165
|
if (["/register", "/authorize", "/callback", "/token"].includes(path)) {
|
|
165
|
-
console.error(`[oauth] ${
|
|
166
|
+
console.error(`[oauth] ${path}` +
|
|
166
167
|
(path === "/callback"
|
|
167
|
-
? ` error=${url.searchParams.
|
|
168
|
+
? ` error=${url.searchParams.has("error")} code=${url.searchParams.has("code")} state=${url.searchParams.has("state")}`
|
|
168
169
|
: ""));
|
|
169
170
|
}
|
|
170
171
|
// RFC 9728 — Protected Resource Metadata
|
|
@@ -276,7 +277,7 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
276
277
|
await store.del(`pending:${upstreamState}`);
|
|
277
278
|
if (err || !code) {
|
|
278
279
|
const dest = new URL(p.clientRedirectUri);
|
|
279
|
-
dest.searchParams.set("error", err
|
|
280
|
+
dest.searchParams.set("error", oauthErrorCode(err, 'invalid_request'));
|
|
280
281
|
if (p.clientState)
|
|
281
282
|
dest.searchParams.set("state", p.clientState);
|
|
282
283
|
res.writeHead(302, { Location: dest.toString() });
|
|
@@ -302,8 +303,10 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
302
303
|
tokenJson = JSON.parse(rawTok);
|
|
303
304
|
}
|
|
304
305
|
catch { /* non-JSON */ }
|
|
305
|
-
if (!tokenRes.ok ||
|
|
306
|
-
|
|
306
|
+
if (!tokenRes.ok || typeof tokenJson?.access_token !== 'string' || !tokenJson.access_token) {
|
|
307
|
+
logSafeError('[oauth] /callback Entra token exchange FAILED', {
|
|
308
|
+
status: tokenRes.status, code: oauthErrorCode(tokenJson?.error)
|
|
309
|
+
});
|
|
307
310
|
const dest = new URL(p.clientRedirectUri);
|
|
308
311
|
dest.searchParams.set("error", "server_error");
|
|
309
312
|
if (p.clientState)
|
|
@@ -347,7 +350,7 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
347
350
|
return true;
|
|
348
351
|
}
|
|
349
352
|
if (form["client_id"] && form["client_id"] !== issued.clientId) {
|
|
350
|
-
console.error(
|
|
353
|
+
console.error('[oauth] /token authorization_code: client mismatch');
|
|
351
354
|
sendJson(res, 400, { error: "invalid_client" });
|
|
352
355
|
return true;
|
|
353
356
|
}
|
|
@@ -369,18 +372,19 @@ export async function handleOAuthRoutes(req, res, cfg) {
|
|
|
369
372
|
}),
|
|
370
373
|
});
|
|
371
374
|
const refreshJson = await refreshRes.json().catch(() => null);
|
|
372
|
-
|
|
375
|
+
const refreshed = refreshRes.ok && typeof refreshJson?.access_token === 'string' && !!refreshJson.access_token;
|
|
376
|
+
if (refreshed) {
|
|
373
377
|
// Never log the body here: on success it carries the access and refresh tokens.
|
|
374
378
|
console.error("[oauth] /token refresh_token: OK");
|
|
375
379
|
}
|
|
376
380
|
else {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
console.error(`[oauth] /token refresh_token: FAILED status=${refreshRes.status} ` +
|
|
381
|
-
`error=${refreshJson?.error ?? "unknown"} desc=${(refreshJson?.error_description ?? "").slice(0, 300)}`);
|
|
381
|
+
logSafeError('[oauth] /token refresh_token: FAILED', {
|
|
382
|
+
status: refreshRes.status, code: oauthErrorCode(refreshJson?.error, 'invalid_grant')
|
|
383
|
+
});
|
|
382
384
|
}
|
|
383
|
-
sendJson(res,
|
|
385
|
+
sendJson(res, refreshed ? 200 : 400, refreshed ? refreshJson : {
|
|
386
|
+
error: oauthErrorCode(refreshJson?.error, 'invalid_grant')
|
|
387
|
+
});
|
|
384
388
|
return true;
|
|
385
389
|
}
|
|
386
390
|
sendJson(res, 400, { error: "unsupported_grant_type" });
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { BookStackClient } from './bookstack-client.js';
|
|
3
|
+
const requests = new AsyncLocalStorage();
|
|
4
|
+
export function parseRequestCredentials(headers, enabled) {
|
|
5
|
+
if (!enabled)
|
|
6
|
+
return undefined;
|
|
7
|
+
const tokenId = headers['x-bookstack-token-id'];
|
|
8
|
+
const tokenSecret = headers['x-bookstack-token-secret'];
|
|
9
|
+
if (tokenId === undefined && tokenSecret === undefined)
|
|
10
|
+
return undefined;
|
|
11
|
+
if (typeof tokenId !== 'string' || typeof tokenSecret !== 'string' ||
|
|
12
|
+
!tokenId.trim() || !tokenSecret.trim() || /[\s:,]/.test(tokenId) || /[\s,]/.test(tokenSecret)) {
|
|
13
|
+
throw new Error('Supply both X-Bookstack-Token-Id and X-Bookstack-Token-Secret as single non-empty credentials.');
|
|
14
|
+
}
|
|
15
|
+
return { tokenId, tokenSecret };
|
|
16
|
+
}
|
|
17
|
+
export function withRequestCredentials(credentials, fn) {
|
|
18
|
+
return requests.run({ credentials, clients: new Map() }, fn);
|
|
19
|
+
}
|
|
20
|
+
/** Tool/resource closures use the current HTTP request identity, including when
|
|
21
|
+
* a session is reused. Each request owns its clients and private slug caches. */
|
|
22
|
+
export function requestScopedClient(config) {
|
|
23
|
+
const fallback = new BookStackClient(config);
|
|
24
|
+
return new Proxy(fallback, {
|
|
25
|
+
get(target, property) {
|
|
26
|
+
const request = requests.getStore();
|
|
27
|
+
let selected = target;
|
|
28
|
+
if (request?.credentials) {
|
|
29
|
+
selected = request.clients.get(target);
|
|
30
|
+
if (!selected) {
|
|
31
|
+
selected = new BookStackClient({ ...config, ...request.credentials, privateSlugCache: true });
|
|
32
|
+
request.clients.set(target, selected);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const value = Reflect.get(selected, property);
|
|
36
|
+
return typeof value === 'function' ? value.bind(selected) : value;
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { AxiosError } from 'axios';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
|
+
import { PublicError } from './safe-errors.js';
|
|
4
|
+
const MAX_RETRIES = 5;
|
|
5
|
+
const MAX_DELAY_MS = 30000;
|
|
6
|
+
export function retryDelay(value, retry) {
|
|
7
|
+
let delay = 1000 * 2 ** (retry - 1);
|
|
8
|
+
if (typeof value === 'string' && value.trim()) {
|
|
9
|
+
const seconds = Number(value);
|
|
10
|
+
const parsed = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
|
|
11
|
+
if (Number.isFinite(parsed))
|
|
12
|
+
delay = parsed;
|
|
13
|
+
}
|
|
14
|
+
return Math.min(MAX_DELAY_MS, Math.max(0, delay));
|
|
15
|
+
}
|
|
16
|
+
export class BookStackRateLimitError extends PublicError {
|
|
17
|
+
retryAfterMs;
|
|
18
|
+
code = 'BOOKSTACK_RATE_LIMITED';
|
|
19
|
+
status = 429;
|
|
20
|
+
constructor(retryAfterMs) {
|
|
21
|
+
super('BookStack rate limited (HTTP 429): retry budget exhausted. Try again later or reduce parallel tool calls.');
|
|
22
|
+
this.retryAfterMs = retryAfterMs;
|
|
23
|
+
this.name = 'BookStackRateLimitError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** One budget covers queueing, HTTP attempts and backoff. Permits are released
|
|
27
|
+
* during backoff, and cancellation removes queued work instead of leaking it. */
|
|
28
|
+
export function rateLimitedAdapter(adapter, limiter, budgetMs) {
|
|
29
|
+
return async (config) => {
|
|
30
|
+
const controller = new AbortController();
|
|
31
|
+
const originalSignal = config.signal;
|
|
32
|
+
const cancel = () => controller.abort();
|
|
33
|
+
if (originalSignal?.aborted)
|
|
34
|
+
cancel();
|
|
35
|
+
originalSignal?.addEventListener?.('abort', cancel);
|
|
36
|
+
const deadline = Date.now() + budgetMs;
|
|
37
|
+
const timeoutError = new AxiosError('BookStack request deadline exceeded', 'ETIMEDOUT', config);
|
|
38
|
+
const timer = setTimeout(() => controller.abort(timeoutError), budgetMs);
|
|
39
|
+
let last429;
|
|
40
|
+
let delay = 0;
|
|
41
|
+
try {
|
|
42
|
+
for (let retry = 0;; retry++) {
|
|
43
|
+
try {
|
|
44
|
+
return await limiter.run(() => {
|
|
45
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
46
|
+
return adapter({
|
|
47
|
+
...config,
|
|
48
|
+
signal: controller.signal,
|
|
49
|
+
timeout: config.timeout > 0 ? Math.min(config.timeout, remaining) : remaining
|
|
50
|
+
});
|
|
51
|
+
}, controller.signal);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (controller.signal.aborted)
|
|
55
|
+
throw error;
|
|
56
|
+
if (!(error instanceof AxiosError) || error.response?.status !== 429)
|
|
57
|
+
throw error;
|
|
58
|
+
last429 = error;
|
|
59
|
+
delay = retryDelay(error.response.headers?.['retry-after'], retry + 1);
|
|
60
|
+
if (retry >= MAX_RETRIES || delay >= deadline - Date.now()) {
|
|
61
|
+
throw new BookStackRateLimitError(delay);
|
|
62
|
+
}
|
|
63
|
+
console.error(`BookStack rate limited (429); retry ${retry + 1}/${MAX_RETRIES} in ${delay}ms`);
|
|
64
|
+
await sleep(delay, undefined, { signal: controller.signal });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (controller.signal.aborted && !originalSignal?.aborted) {
|
|
70
|
+
if (last429)
|
|
71
|
+
throw new BookStackRateLimitError(delay);
|
|
72
|
+
throw timeoutError;
|
|
73
|
+
}
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
originalSignal?.removeEventListener?.('abort', cancel);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Messages authored by this application, rather than supplied by a remote
|
|
2
|
+
* service or a library. Only these messages may reach MCP clients unchanged. */
|
|
3
|
+
export class PublicError extends Error {
|
|
4
|
+
}
|
|
5
|
+
const OAUTH_CODES = new Set([
|
|
6
|
+
'invalid_grant', 'invalid_client', 'invalid_request', 'unauthorized_client',
|
|
7
|
+
'access_denied', 'temporarily_unavailable', 'server_error', 'invalid_scope',
|
|
8
|
+
'interaction_required', 'consent_required', 'login_required'
|
|
9
|
+
]);
|
|
10
|
+
const SAFE_CODES = new Set([
|
|
11
|
+
'ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT',
|
|
12
|
+
'ECONNABORTED', 'ERR_NETWORK', 'ERR_CANCELED', 'ERR_BAD_REQUEST',
|
|
13
|
+
'ERR_BAD_RESPONSE', 'ERR_INVALID_URL', 'ENOENT', 'EACCES', 'BOOKSTACK_RATE_LIMITED',
|
|
14
|
+
...OAUTH_CODES
|
|
15
|
+
]);
|
|
16
|
+
/** Allowlist fields, not a recursive dump/redaction of arbitrary error objects.
|
|
17
|
+
* In particular, messages, stacks, causes, config, headers and bodies are omitted. */
|
|
18
|
+
export function safeErrorDetails(error) {
|
|
19
|
+
try {
|
|
20
|
+
if (!error || typeof error !== 'object')
|
|
21
|
+
return {};
|
|
22
|
+
const value = error;
|
|
23
|
+
const status = value.response?.status ?? value.status;
|
|
24
|
+
return {
|
|
25
|
+
...(typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599 ? { status } : {}),
|
|
26
|
+
...(typeof value.code === 'string' && SAFE_CODES.has(value.code) ? { code: value.code } : {})
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return {}; // A throwing getter must not defeat the error boundary.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function safeError(error, context = 'Operation failed') {
|
|
34
|
+
if (error instanceof PublicError)
|
|
35
|
+
return error;
|
|
36
|
+
const { status, code } = safeErrorDetails(error);
|
|
37
|
+
const details = [status === undefined ? '' : `HTTP ${status}`, code ?? ''].filter(Boolean);
|
|
38
|
+
const result = new PublicError(`${context}${details.length ? ` (${details.join('; ')})` : ''}`);
|
|
39
|
+
return Object.assign(result, safeErrorDetails(error));
|
|
40
|
+
}
|
|
41
|
+
export function logSafeError(event, error) {
|
|
42
|
+
console.error(event, safeErrorDetails(error));
|
|
43
|
+
}
|
|
44
|
+
export function safeUrlOrigin(value) {
|
|
45
|
+
try {
|
|
46
|
+
const url = new URL(value);
|
|
47
|
+
return ['http:', 'https:'].includes(url.protocol) ? url.origin : '<invalid URL>';
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return '<invalid URL>';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function oauthErrorCode(value, fallback = 'server_error') {
|
|
54
|
+
return typeof value === 'string' && OAUTH_CODES.has(value) ? value : fallback;
|
|
55
|
+
}
|
package/dist/util/semaphore.js
CHANGED
|
@@ -12,12 +12,27 @@ export class Semaphore {
|
|
|
12
12
|
}
|
|
13
13
|
this.permits = max;
|
|
14
14
|
}
|
|
15
|
-
acquire() {
|
|
15
|
+
acquire(signal) {
|
|
16
|
+
if (signal?.aborted)
|
|
17
|
+
return Promise.reject(signal.reason);
|
|
16
18
|
if (this.permits > 0) {
|
|
17
19
|
this.permits--;
|
|
18
20
|
return Promise.resolve();
|
|
19
21
|
}
|
|
20
|
-
return new Promise((resolve) =>
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const grant = () => {
|
|
24
|
+
signal?.removeEventListener('abort', cancel);
|
|
25
|
+
resolve();
|
|
26
|
+
};
|
|
27
|
+
const cancel = () => {
|
|
28
|
+
const index = this.waiters.indexOf(grant);
|
|
29
|
+
if (index !== -1)
|
|
30
|
+
this.waiters.splice(index, 1);
|
|
31
|
+
reject(signal.reason);
|
|
32
|
+
};
|
|
33
|
+
this.waiters.push(grant);
|
|
34
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
35
|
+
});
|
|
21
36
|
}
|
|
22
37
|
release() {
|
|
23
38
|
const next = this.waiters.shift();
|
|
@@ -28,9 +43,11 @@ export class Semaphore {
|
|
|
28
43
|
this.permits++;
|
|
29
44
|
}
|
|
30
45
|
}
|
|
31
|
-
async run(fn) {
|
|
32
|
-
await this.acquire();
|
|
46
|
+
async run(fn, signal) {
|
|
47
|
+
await this.acquire(signal);
|
|
33
48
|
try {
|
|
49
|
+
if (signal?.aborted)
|
|
50
|
+
throw signal.reason;
|
|
34
51
|
return await fn();
|
|
35
52
|
}
|
|
36
53
|
finally {
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bookstack-mcp",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.5.0",
|
|
4
4
|
"description": "MCP server for BookStack wiki — search, read, create, and manage documentation via AI assistants",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"bookstack-mcp": "dist/index.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
|
-
"dist"
|
|
10
|
+
"dist",
|
|
11
|
+
"PRIVACY.md"
|
|
11
12
|
],
|
|
12
13
|
"scripts": {
|
|
13
14
|
"build": "tsc && shx chmod +x dist/*.js",
|
|
@@ -45,12 +46,12 @@
|
|
|
45
46
|
"axios": "^1.6.0",
|
|
46
47
|
"ioredis": "^5.11.1",
|
|
47
48
|
"jose": "^6.2.3",
|
|
48
|
-
"zod": "^
|
|
49
|
+
"zod": "^4.6.5"
|
|
49
50
|
},
|
|
50
51
|
"devDependencies": {
|
|
51
|
-
"@types/node": "^
|
|
52
|
+
"@types/node": "^26.6.3",
|
|
52
53
|
"shx": "^0.4.0",
|
|
53
54
|
"tsx": "^4.6.0",
|
|
54
|
-
"typescript": "^
|
|
55
|
+
"typescript": "^7.0.2"
|
|
55
56
|
}
|
|
56
57
|
}
|