@archbee/mcp 1.1.23 → 2.1.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/README.md CHANGED
@@ -1,28 +1,72 @@
1
1
  # Archbee MCP Server
2
2
 
3
- This is a Model Context Protocol (MCP) server for interacting with the [Archbee API](https://docs.archbee.com/get-document). This server provides tools to read, search and list Archbee documents from your space using Large Language Models.
3
+ A Model Context Protocol (MCP) server for the [Archbee API](https://docs.archbee.com/get-document). It lets an LLM client read, search, create, update and delete the documentation in your Archbee space.
4
+
5
+ With a space API key every tool acts on that one space, and `docSpaceId` never has to be passed in. With a team key (`abteam_…`) the assistant reaches every space in the team, and the space-level tools take a `docSpaceId` argument per call.
4
6
 
5
7
  ### Tools
6
8
 
7
- 1. get-doc
9
+ Read:
10
+
11
+ 1. `get_doc`
8
12
  - Gets content of a document
9
13
  - Input:
10
- - id (string): Archbee id
11
- - Returns: Content as markdown
12
- 2. get-all-docs
13
- - Gets content of all documents in space
14
- - Returns: documents, as DocResponse\[]
15
- 3. search-query
16
- - Search docs by input query
17
- - if query is empty, return all docs
14
+ - `docId` (string): Archbee document id
15
+ - Returns: content as markdown
16
+ 2. `get_all_docs`
17
+ - Gets content of all documents in the space
18
+ - Returns: documents, as `DocResponse[]`
19
+ 3. `search_query`
20
+ - Searches docs by content; an empty query returns all docs
18
21
  - Input:
19
- - query (string): text as part of documents to search
20
- - Returns: documents containing query, as DocResponse\[]
21
- 4. search-title
22
- - Search docs by input title
22
+ - `query` (string): text to look for inside documents
23
+ - Returns: documents containing the query, as `DocResponse[]`
24
+ 4. `search_title`
25
+ - Searches docs by title
23
26
  - Input:
24
- - query (string): text as part of titles to search
25
- - Returns: documents with title containing query, as DocResponse\[]
27
+ - `query` (string): text to look for in titles
28
+ - Returns: documents with a matching title, as `DocResponse[]`
29
+
30
+ Write — these need an API key, space or team (the configurations below):
31
+
32
+ 5. `create_doc`
33
+ - Creates a document from Markdown or MDX content
34
+ - Input:
35
+ - `content` (string): body as Markdown or MDX text
36
+ - `format` (`markdown` | `mdx`, optional): use `mdx` for JSX-style components such as `<hint>` or `<Tabs>`; directive-style (`:::hint{type="info"}`) works in both. Defaults to `markdown`
37
+ - also optional: `title`, `parentDocId`, `slug`, `description`, `previewImgURL`, `hidden`
38
+ 6. `update_doc`
39
+ - Updates a document; only the fields you send are changed
40
+ - Input:
41
+ - `docId` (string): document to update
42
+ - optional: `content`, `format`, `title`, `parentDocId`, `slug`, `description`, `previewImgURL`, `hidden`
43
+ 7. `delete_doc`
44
+ - Permanently deletes a document, its uploaded files and images. Cannot be undone
45
+ - Input:
46
+ - `docId` (string): document to delete
47
+ - `recursive` (boolean, optional): required to delete a document that has nested children, which deletes them too
48
+ 8. `create_doc_space`
49
+ - Creates a doc space in the team
50
+ - Input:
51
+ - `name` (string): name of the new space
52
+ - optional: `isReviewSystemEnabled`, `isBranchingSystemEnabled`, `docSpaceGroupId`
53
+ 9. `update_doc_space`
54
+ - Updates settings of the configured space; only the parts you send are changed
55
+ - Input, all optional:
56
+ - `hostnamePart` (`{ hostname, hostnamePath }`): custom hostname configuration
57
+ - `spaceLinks` (`{ label, docSpaceId }[]`): links to other spaces; the list should start with the current space
58
+ - `publicAccessControlPart`: public access control and authentication configuration
59
+ 10. `delete_doc_space`
60
+ - Permanently deletes the configured space and every document in it. Cannot be undone, and the `API_KEY` dies with it
61
+ 11. `create_space_group`
62
+ - Creates a space group. Requires a team admin
63
+ - Input:
64
+ - `name` (string): name of the new group
65
+ - optional: `isAiEnabled`, `isReviewSystemEnabled`, `isBranchingSystemEnabled`
66
+ 12. `delete_space_group`
67
+ - Deletes an empty space group. Requires a team admin
68
+ - Input:
69
+ - `docSpaceGroupId` (string): group to delete
26
70
 
27
71
  ## Setup
28
72
 
@@ -30,6 +74,8 @@ Add this server to your `claude_desktop_config.json` or `.cursor/mcp.json`
30
74
 
31
75
  ### Environment Variables - base link
32
76
 
77
+ Read-only. Use this for a public space.
78
+
33
79
  - `API_BASE`: Link to your Archbee portal
34
80
 
35
81
  Space must be public, with no access control (no password, jwt etc)
@@ -39,8 +85,8 @@ Just copy-paste the link to the archbee space.
39
85
  {
40
86
  "mcpServers": {
41
87
  "archbee": {
42
- "command": "npx",
43
- "args": ["-y", "@archbee/mcp"],
88
+ "command": "pnpm",
89
+ "args": ["dlx", "@archbee/mcp"],
44
90
  "env": {
45
91
  "API_BASE": "https://your-docs.io/"
46
92
  }
@@ -51,20 +97,23 @@ Just copy-paste the link to the archbee space.
51
97
 
52
98
  ### Environment Variables - space id
53
99
 
54
- Alternatively, you can set space id, which can also be used for internal spaces.
100
+ Required for the write tools, and also works for reading internal spaces.
55
101
 
56
102
  You can get an API token from Space Settings in Archbee app.
57
- Your space must be published with that apiKey.
58
103
 
59
- - `SPACE_ID`: Space id starting with `PUBLISHED-`
104
+ - `SPACE_ID`: Space id, taken from the space URL in the app
60
105
  - `API_KEY`: Your Archbee API token for that Space
61
106
 
107
+ Use the live space id here. A `PUBLISHED-` or `PREVIEW-` snapshot id reads fine, but the API refuses every write through a snapshot credential.
108
+
109
+ A space API key belongs to one space, so this configuration reads and writes that space only. For every space in the team, use a team key instead.
110
+
62
111
  ```json
63
112
  {
64
113
  "mcpServers": {
65
114
  "archbee": {
66
- "command": "npx",
67
- "args": ["-y", "@archbee/mcp"],
115
+ "command": "pnpm",
116
+ "args": ["dlx", "@archbee/mcp"],
68
117
  "env": {
69
118
  "SPACE_ID": "<id-of-space>",
70
119
  "API_KEY": "<api-key-of-space>"
@@ -73,3 +122,50 @@ Your space must be published with that apiKey.
73
122
  }
74
123
  }
75
124
  ```
125
+
126
+ ### Environment Variables - team key
127
+
128
+ Reads and writes every space in the team. The organization super-admin creates the key in Settings → Organization settings → Organization API key; it is shown once, on creation, and cannot be read back afterwards. Revoking it stops every assistant configured with it.
129
+
130
+ - `API_KEY`: Team key, starting with `abteam_`
131
+
132
+ A team key is accepted on the MCP endpoints only — the rest of the Public API and the CLI still take a space key.
133
+
134
+ No `SPACE_ID`: the key is not bound to a space, so the space travels per call. `get_doc`, `get_all_docs`, `search_query`, `search_title`, `create_doc`, `update_doc`, `delete_doc`, `update_doc_space` and `delete_doc_space` take a `docSpaceId` argument; `create_doc_space`, `create_space_group` and `delete_space_group` act on the team and take none.
135
+
136
+ ```json
137
+ {
138
+ "mcpServers": {
139
+ "archbee": {
140
+ "command": "pnpm",
141
+ "args": ["dlx", "@archbee/mcp"],
142
+ "env": {
143
+ "API_KEY": "abteam_<team-key>"
144
+ }
145
+ }
146
+ }
147
+ }
148
+ ```
149
+
150
+ ### Environment Variables - other Archbee installs
151
+
152
+ Both API-key configurations talk to `https://api.archbee.com` by default — the same host the Archbee CLI and the public API reference use. Point them elsewhere with:
153
+
154
+ - `ARCHBEE_API_URL`: Origin of your Archbee API, e.g. `https://qa.archbee.com` or `http://localhost:4000`
155
+
156
+ Give the origin only — the server appends `/api/public-mcp` itself. A value without a scheme is rejected rather than silently falling back to the cloud. `API_BASE` (the public-portal configuration) is a full link and ignores this.
157
+
158
+ ```json
159
+ {
160
+ "mcpServers": {
161
+ "archbee": {
162
+ "command": "pnpm",
163
+ "args": ["dlx", "@archbee/mcp"],
164
+ "env": {
165
+ "ARCHBEE_API_URL": "https://qa.archbee.com",
166
+ "API_KEY": "abteam_<team-key>"
167
+ }
168
+ }
169
+ }
170
+ }
171
+ ```
package/dist/index.js CHANGED
@@ -6,40 +6,251 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
8
8
  const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
9
- const zod_1 = require("zod");
10
9
  const axios_1 = __importDefault(require("axios"));
10
+ const zod_1 = require("zod");
11
+ // A team key is not bound to a space, so the space travels per call instead of
12
+ // being packed into the credential like a space key is.
13
+ const TEAM_API_KEY_PREFIX = 'abteam_';
14
+ const usesTeamApiKey = () => (process.env.API_KEY || '').startsWith(TEAM_API_KEY_PREFIX);
15
+ const docSpaceIdArg = {
16
+ docSpaceId: zod_1.z
17
+ .string()
18
+ .optional()
19
+ .describe('Space to act on. Required when API_KEY is a team key (starts with `abteam_`), which can reach every space in the team. Ignored with a space API key, since that key already names its space.'),
20
+ };
21
+ const MDX_FORMAT_DESCRIPTION = 'Format of `content`. Use `mdx` when the content contains JSX-style Archbee components such as `<hint>`, `<CtaButton />` or `<Tabs>` — with plain markdown those degrade to raw html blocks. Directive-style components (`:::hint{type="info"}`) work in both formats. Defaults to markdown when omitted.';
11
22
  // Create an MCP server
12
23
  const server = new mcp_js_1.McpServer({
13
24
  name: 'Archbee MCP',
14
- version: '1.0.0',
25
+ version: '2.1.0',
15
26
  });
16
- server.tool('get_all_docs', {}, async ({}) => {
27
+ server.tool('get_all_docs', 'Read every document in the Archbee doc space, with its content, and each document carries the name of the space it belongs to (docSpaceName). Returns the whole space, so prefer search_query or search_title when looking for something specific.', { ...docSpaceIdArg }, async ({ docSpaceId }) => {
17
28
  const params = {
18
29
  tool: 'get-all-docs',
30
+ docSpaceId,
19
31
  };
20
32
  return callMcpApi(params);
21
33
  });
22
- server.tool('get_doc', { docId: zod_1.z.string() }, async ({ docId }) => {
34
+ server.tool('get_doc', 'Read one Archbee document by id and return its content as markdown, alongside the id and name of the space it lives in.', {
35
+ docId: zod_1.z
36
+ .string()
37
+ .describe('ID of the document to read, as returned by search_query, search_title or get_all_docs.'),
38
+ ...docSpaceIdArg,
39
+ }, async ({ docId, docSpaceId }) => {
23
40
  const params = {
24
41
  tool: 'get-doc',
25
42
  docId,
43
+ docSpaceId,
26
44
  };
27
45
  return callMcpApi(params);
28
46
  });
29
- server.tool('search_query', { query: zod_1.z.string() }, async ({ query }) => {
47
+ server.tool('search_query', 'Search the Archbee doc space by document content and return the matching documents. This is the tool to use for answering a question from the documentation. An empty query returns every document.', {
48
+ query: zod_1.z
49
+ .string()
50
+ .describe('Text to look for inside the content of the documents.'),
51
+ ...docSpaceIdArg,
52
+ }, async ({ query, docSpaceId }) => {
30
53
  const params = {
31
54
  tool: 'search-query',
32
55
  query,
56
+ docSpaceId,
33
57
  };
34
58
  return callMcpApi(params);
35
59
  });
36
- server.tool('search_title', { query: zod_1.z.string() }, async ({ query }) => {
60
+ server.tool('search_title', 'Search the Archbee doc space by document title. Use this when looking for a page by name; use search_query to search inside document content.', {
61
+ query: zod_1.z.string().describe('Text to look for in the document titles.'),
62
+ ...docSpaceIdArg,
63
+ }, async ({ query, docSpaceId }) => {
37
64
  const params = {
38
65
  tool: 'search-title',
39
66
  query,
67
+ docSpaceId,
40
68
  };
41
69
  return callMcpApi(params);
42
70
  });
71
+ // Write tools. With a space key the target space comes from SPACE_ID; with a
72
+ // team key it comes from the docSpaceId argument, which the three team-level
73
+ // tools below do not take because they act on the team, not on a space.
74
+ server.tool('create_doc', 'Create a new document in the Archbee doc space from Markdown or MDX content.', {
75
+ content: zod_1.z
76
+ .string()
77
+ .describe('Body of the document to create, as Markdown or MDX text. JSON document content is not accepted.'),
78
+ format: zod_1.z
79
+ .enum(['markdown', 'mdx'])
80
+ .optional()
81
+ .describe(MDX_FORMAT_DESCRIPTION),
82
+ title: zod_1.z.string().optional().describe('Title of the document.'),
83
+ parentDocId: zod_1.z
84
+ .string()
85
+ .optional()
86
+ .describe('ID of the parent document to nest this document under.'),
87
+ slug: zod_1.z.string().optional().describe('URL slug for the document.'),
88
+ description: zod_1.z
89
+ .string()
90
+ .optional()
91
+ .describe('Short description / summary of the document.'),
92
+ previewImgURL: zod_1.z
93
+ .string()
94
+ .optional()
95
+ .describe('URL of the preview / social image for the document.'),
96
+ hidden: zod_1.z
97
+ .boolean()
98
+ .optional()
99
+ .describe('When true, the document is hidden from navigation.'),
100
+ ...docSpaceIdArg,
101
+ }, async (args) => callWriteApi({ tool: 'create-doc', ...args }));
102
+ server.tool('update_doc', 'Update an existing Archbee document. Only the provided fields are changed.', {
103
+ docId: zod_1.z.string().describe('ID of the document to update.'),
104
+ content: zod_1.z
105
+ .string()
106
+ .optional()
107
+ .describe('New body for the document, as Markdown or MDX text. JSON document content is not accepted.'),
108
+ format: zod_1.z
109
+ .enum(['markdown', 'mdx'])
110
+ .optional()
111
+ .describe(MDX_FORMAT_DESCRIPTION),
112
+ title: zod_1.z.string().optional().describe('New title of the document.'),
113
+ parentDocId: zod_1.z
114
+ .string()
115
+ .optional()
116
+ .describe('ID of the parent document to move this document under.'),
117
+ slug: zod_1.z.string().optional().describe('New URL slug for the document.'),
118
+ description: zod_1.z
119
+ .string()
120
+ .optional()
121
+ .describe('New short description / summary of the document.'),
122
+ previewImgURL: zod_1.z
123
+ .string()
124
+ .optional()
125
+ .describe('New preview / social image URL for the document.'),
126
+ hidden: zod_1.z
127
+ .boolean()
128
+ .optional()
129
+ .describe('When true, the document is hidden from navigation.'),
130
+ ...docSpaceIdArg,
131
+ }, async (args) => callWriteApi({ tool: 'update-doc', ...args }));
132
+ server.tool('delete_doc', 'Permanently delete an Archbee document. This is destructive and cannot be undone: the document is removed together with every file and image uploaded to it, and any documents nested underneath it are deleted as well. Ask the user to confirm before calling this tool.', {
133
+ docId: zod_1.z.string().describe('ID of the document to delete.'),
134
+ recursive: zod_1.z
135
+ .boolean()
136
+ .optional()
137
+ .describe('Required (set to true) to delete a document that has nested child documents, which deletes those children too. When the document has children and this is not set, the call is rejected and the response lists the child documents that would be affected.'),
138
+ ...docSpaceIdArg,
139
+ }, async (args) => callWriteApi({ tool: 'delete-doc', ...args }));
140
+ server.tool('create_doc_space', 'Create a new doc space (documentation space) in the current Archbee team.', {
141
+ name: zod_1.z.string().describe('Name of the new doc space.'),
142
+ isReviewSystemEnabled: zod_1.z
143
+ .boolean()
144
+ .optional()
145
+ .describe('Enable the review/approval workflow for the space.'),
146
+ isBranchingSystemEnabled: zod_1.z
147
+ .boolean()
148
+ .optional()
149
+ .describe('Enable the branching (git-style) workflow for the space.'),
150
+ docSpaceGroupId: zod_1.z
151
+ .string()
152
+ .optional()
153
+ .describe('ID of the collection/group to place the new space in.'),
154
+ }, async (args) => callWriteApi({ tool: 'create-doc-space', ...args }));
155
+ // Mirrors PublicAPIUpdateDocSpaceRequestSchema in @archbee/data-access, which
156
+ // this standalone package cannot import. The API re-validates with the real
157
+ // schema, so this only has to describe the shape well enough for the model;
158
+ // publicAccessControlPart passes unknown keys through so newer access-control
159
+ // fields keep working without a release here.
160
+ const emailListSchema = zod_1.z.array(zod_1.z.object({ email: zod_1.z.string() }));
161
+ const publicAccessControlPartSchema = zod_1.z
162
+ .object({
163
+ publicProtectionTypes: zod_1.z
164
+ .array(zod_1.z.enum([
165
+ 'None',
166
+ 'Password',
167
+ 'Guest accounts',
168
+ 'Private Accounts',
169
+ 'Private Link',
170
+ 'Magic Link',
171
+ 'JWT',
172
+ 'SAML',
173
+ 'OIDC',
174
+ ]))
175
+ .optional(),
176
+ publicPassword: zod_1.z.string().optional(),
177
+ publicGuestAccounts: zod_1.z
178
+ .array(zod_1.z.object({ email: zod_1.z.string(), password: zod_1.z.string() }))
179
+ .optional(),
180
+ publicMagicLinkAccounts: emailListSchema.optional(),
181
+ publicPrivateAccounts: emailListSchema.optional(),
182
+ jwtValidationType: zod_1.z.string().optional(),
183
+ jwtKeyUrl: zod_1.z.string().optional(),
184
+ jwtSecret: zod_1.z.string().optional(),
185
+ jwtRedirectURL: zod_1.z.string().optional(),
186
+ samlMetadata: zod_1.z.string().optional(),
187
+ samlEntityId: zod_1.z.string().optional(),
188
+ conditionalRuleId: zod_1.z.string().optional(),
189
+ })
190
+ .passthrough();
191
+ server.tool('update_doc_space', 'Update an Archbee doc space: rename it, or change its hostname, space links or public access control. Only the provided parts are changed, and at least one must be provided. The response echoes the space name, and get_all_docs / get_doc report it too, so a rename can be verified.', {
192
+ name: zod_1.z
193
+ .string()
194
+ .optional()
195
+ .describe('New display name for the space (renames it).'),
196
+ hostnamePart: zod_1.z
197
+ .object({ hostname: zod_1.z.string(), hostnamePath: zod_1.z.string() })
198
+ .optional()
199
+ .describe('Custom hostname configuration for the space.'),
200
+ spaceLinks: zod_1.z
201
+ .array(zod_1.z.object({ label: zod_1.z.string(), docSpaceId: zod_1.z.string() }))
202
+ .optional()
203
+ .describe('Links to other spaces. The list should start with the current space.'),
204
+ publicAccessControlPart: publicAccessControlPartSchema
205
+ .optional()
206
+ .describe('Public access control and authentication configuration.'),
207
+ ...docSpaceIdArg,
208
+ }, async (args) => callWriteApi({ tool: 'update-doc-space', ...args }));
209
+ server.tool('delete_doc_space', 'Permanently delete an Archbee doc space together with every document inside it. This is destructive and cannot be undone. With a space API key the space deleted is the one SPACE_ID points at, so that key dies with it and no further tool call will work; with a team key it is the space named by docSpaceId. Ask the user to confirm before calling this tool.', { ...docSpaceIdArg }, async (args) => callWriteApi({ tool: 'delete-doc-space', ...args }));
210
+ server.tool('create_space_group', 'Create a new space group (collection of doc spaces) in the current Archbee team. Requires a team admin.', {
211
+ name: zod_1.z.string().describe('Name of the new space group.'),
212
+ isAiEnabled: zod_1.z
213
+ .boolean()
214
+ .optional()
215
+ .describe('Enable AI features for the space group.'),
216
+ isReviewSystemEnabled: zod_1.z
217
+ .boolean()
218
+ .optional()
219
+ .describe('Enable the review/approval workflow for the space group.'),
220
+ isBranchingSystemEnabled: zod_1.z
221
+ .boolean()
222
+ .optional()
223
+ .describe('Enable the branching (git-style) workflow for the space group.'),
224
+ }, async (args) => callWriteApi({ tool: 'create-space-group', ...args }));
225
+ server.tool('delete_space_group', 'Delete a space group (collection of doc spaces) from the current Archbee team. Requires a team admin. The group must already be empty: move or delete every doc space it still contains first, otherwise the call is rejected.', {
226
+ docSpaceGroupId: zod_1.z.string().describe('ID of the space group to delete.'),
227
+ }, async (args) => callWriteApi({ tool: 'delete-space-group', ...args }));
228
+ server.tool('create_category', 'Create a category (a folder in the space navigation) in an Archbee doc space. A category holds documents but has no content of its own. To put a document inside it, pass the returned categoryId as `parentDocId` on create_doc or update_doc.', {
229
+ categoryName: zod_1.z.string().describe('Name of the category to create.'),
230
+ parentDocId: zod_1.z
231
+ .string()
232
+ .optional()
233
+ .describe('ID of the document or category to nest this category under. Omit to create it at the top level of the space.'),
234
+ ...docSpaceIdArg,
235
+ }, async (args) => callWriteApi({ tool: 'create-category', ...args }));
236
+ server.tool('delete_category', 'Delete a category from an Archbee doc space. The category must already be empty: move or delete the documents inside it first, otherwise the call is rejected. Deleting a category never deletes documents.', {
237
+ categoryId: zod_1.z.string().describe('ID of the category to delete.'),
238
+ ...docSpaceIdArg,
239
+ }, async (args) => callWriteApi({ tool: 'delete-category', ...args }));
240
+ // Origin of the Archbee API the key belongs to, same variable the CLI takes.
241
+ // app.archbee.com/api is being phased out, so the default is api.archbee.com.
242
+ const apiMcpUrl = () => {
243
+ const apiUrlInput = (process.env.ARCHBEE_API_URL || '').trim();
244
+ if (!apiUrlInput) {
245
+ return 'https://api.archbee.com/api/public-mcp';
246
+ }
247
+ try {
248
+ return new URL('/api/public-mcp', apiUrlInput).toString();
249
+ }
250
+ catch {
251
+ return null;
252
+ }
253
+ };
43
254
  const processUrl = (urlInput) => {
44
255
  try {
45
256
  const url = new URL(urlInput);
@@ -48,46 +259,74 @@ const processUrl = (urlInput) => {
48
259
  : url.pathname + '/mcp';
49
260
  return url.toString();
50
261
  }
51
- catch (error) {
262
+ catch {
52
263
  return null;
53
264
  }
54
265
  };
266
+ // A team key authenticates on its own, so team-level tools need no space at all.
267
+ // A space key carries no space id, so it travels packed with one.
268
+ const authorizationHeader = (docSpaceId) => {
269
+ const apiKey = process.env.API_KEY || '';
270
+ if (!apiKey) {
271
+ return '';
272
+ }
273
+ if (usesTeamApiKey()) {
274
+ return `Bearer ${apiKey}`;
275
+ }
276
+ return docSpaceId
277
+ ? `Bearer ${Buffer.from(`${docSpaceId}~${apiKey}`).toString('base64')}`
278
+ : '';
279
+ };
55
280
  const callMcpApi = async (params) => {
56
281
  const urlInput = process.env.API_BASE || '';
57
- const docSpaceIdInput = process.env.SPACE_ID || '';
58
- if (!urlInput && !docSpaceIdInput) {
282
+ const teamMode = usesTeamApiKey();
283
+ const docSpaceIdInput = teamMode
284
+ ? params.docSpaceId || ''
285
+ : process.env.SPACE_ID || '';
286
+ if (!teamMode && !urlInput && !docSpaceIdInput) {
59
287
  return {
60
288
  content: [{ type: 'text', text: 'API base URL or docSpaceId not set.' }],
289
+ isError: true,
61
290
  };
62
291
  }
63
292
  if (!process.env.API_KEY && !urlInput) {
64
- return { content: [{ type: 'text', text: 'API key not set.' }] };
293
+ return {
294
+ content: [{ type: 'text', text: 'API key not set.' }],
295
+ isError: true,
296
+ };
65
297
  }
66
- const urlMcp = urlInput
67
- ? processUrl(urlInput)
68
- : 'https://app.archbee.com/api/public-mcp';
298
+ const urlMcp = urlInput ? processUrl(urlInput) : apiMcpUrl();
69
299
  if (urlMcp === null) {
70
300
  return {
71
- content: [{ type: 'text', text: 'Invalid API base URL format.' }],
301
+ content: [
302
+ {
303
+ type: 'text',
304
+ text: 'Invalid API base URL or ARCHBEE_API_URL format.',
305
+ },
306
+ ],
307
+ isError: true,
72
308
  };
73
309
  }
310
+ const authorization = authorizationHeader(docSpaceIdInput);
74
311
  try {
75
- let dataText = '';
76
- if (docSpaceIdInput) {
77
- params.docSpaceId = docSpaceIdInput;
78
- const rawAuth = `${docSpaceIdInput}~${process.env.API_KEY}`;
79
- const base64Auth = Buffer.from(rawAuth).toString('base64');
312
+ let dataText;
313
+ if (authorization) {
314
+ if (docSpaceIdInput) {
315
+ params.docSpaceId = docSpaceIdInput;
316
+ }
80
317
  const response = await axios_1.default.post(urlMcp, params, {
81
318
  headers: {
82
- Authorization: `Bearer ${base64Auth}`,
319
+ Authorization: authorization,
83
320
  'Content-Type': 'application/json',
84
321
  },
322
+ timeout: 30000,
85
323
  });
86
324
  dataText = JSON.stringify(response.data);
87
325
  }
88
326
  else {
89
327
  const response = await axios_1.default.get(urlMcp, {
90
328
  params,
329
+ timeout: 30000,
91
330
  });
92
331
  dataText = JSON.stringify(response.data);
93
332
  }
@@ -96,20 +335,102 @@ const callMcpApi = async (params) => {
96
335
  };
97
336
  }
98
337
  catch (error) {
338
+ const errorMessage = formatError(error);
339
+ console.error(`MCP API error: ${errorMessage}`);
340
+ return {
341
+ content: [{ type: 'text', text: errorMessage }],
342
+ isError: true,
343
+ };
344
+ }
345
+ };
346
+ // Writes only go through the SPACE_ID + API_KEY path: the API_BASE mode is an
347
+ // unauthenticated GET against a public portal, and the API refuses every write
348
+ // made with a PUBLISHED-/PREVIEW- snapshot credential. Both cases fail here with
349
+ // an explanation rather than as an opaque rejection from the server.
350
+ const callWriteApi = async (params) => {
351
+ const teamMode = usesTeamApiKey();
352
+ const docSpaceIdInput = teamMode
353
+ ? params.docSpaceId || ''
354
+ : process.env.SPACE_ID || '';
355
+ if (!process.env.API_KEY || (!teamMode && !docSpaceIdInput)) {
99
356
  return {
100
357
  content: [
101
358
  {
102
359
  type: 'text',
103
- text: `Error in mcp: ${error} ${urlMcp} ${params}`,
360
+ text: 'Write tools need an API_KEY, plus SPACE_ID when the key is a space key. The API_BASE configuration is read-only.',
104
361
  },
105
362
  ],
363
+ isError: true,
106
364
  };
107
365
  }
366
+ if (docSpaceIdInput.startsWith('PUBLISHED-') ||
367
+ docSpaceIdInput.startsWith('PREVIEW-')) {
368
+ return {
369
+ content: [
370
+ {
371
+ type: 'text',
372
+ text: 'The target space is a published/preview snapshot, which cannot be written to. Use the live space id from the space URL in the Archbee app.',
373
+ },
374
+ ],
375
+ isError: true,
376
+ };
377
+ }
378
+ return callMcpApi(params);
379
+ };
380
+ const formatError = (error) => {
381
+ if (axios_1.default.isAxiosError(error)) {
382
+ if (error.code === 'ECONNABORTED') {
383
+ return 'Request timeout - the server took too long to respond.';
384
+ }
385
+ if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
386
+ return 'Connection failed - unable to reach the API server.';
387
+ }
388
+ if (error.response) {
389
+ const status = error.response.status;
390
+ if (status === 401 || status === 403) {
391
+ return 'Authentication failed - check your API key.';
392
+ }
393
+ if (status === 404) {
394
+ return 'Resource not found - check the document ID.';
395
+ }
396
+ if (status >= 500) {
397
+ return 'Server error - please try again later.';
398
+ }
399
+ return `API error (${status}): ${error.response.statusText}`;
400
+ }
401
+ return `Network error: ${error.message}`;
402
+ }
403
+ if (error instanceof Error) {
404
+ return error.message;
405
+ }
406
+ return 'An unexpected error occurred.';
108
407
  };
109
408
  const main = async () => {
110
- // Start receiving messages on stdin and sending messages on stdout
111
409
  const transport = new stdio_js_1.StdioServerTransport();
112
- await server.connect(transport);
410
+ // Handle graceful shutdown
411
+ const shutdown = async () => {
412
+ console.error('Shutting down MCP server...');
413
+ try {
414
+ await server.close();
415
+ }
416
+ catch {
417
+ // Ignore close errors during shutdown
418
+ }
419
+ process.exit(0);
420
+ };
421
+ process.on('SIGINT', shutdown);
422
+ process.on('SIGTERM', shutdown);
423
+ try {
424
+ await server.connect(transport);
425
+ console.error('Archbee MCP server started successfully');
426
+ }
427
+ catch (error) {
428
+ console.error('Failed to start MCP server:', error instanceof Error ? error.message : error);
429
+ process.exit(1);
430
+ }
113
431
  };
114
- main();
432
+ main().catch((error) => {
433
+ console.error('Fatal error:', error instanceof Error ? error.message : error);
434
+ process.exit(1);
435
+ });
115
436
  //# sourceMappingURL=index.js.map