backlog-mcp-server 0.4.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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja.md +440 -0
  3. package/README.md +501 -0
  4. package/build/backlog/backlogErrorHandler.js +8 -0
  5. package/build/backlog/customFields.js +16 -0
  6. package/build/backlog/parseBacklogAPIError.js +38 -0
  7. package/build/createTranslationHelper.js +28 -0
  8. package/build/handlers/builders/composeToolHandler.js +26 -0
  9. package/build/handlers/transformers/wrapWithErrorHandling.js +4 -0
  10. package/build/handlers/transformers/wrapWithFieldPicking.js +55 -0
  11. package/build/handlers/transformers/wrapWithTokenLimit.js +21 -0
  12. package/build/handlers/transformers/wrapWithToolResult.js +39 -0
  13. package/build/index.js +102 -0
  14. package/build/registerTools.js +37 -0
  15. package/build/tools/addIssue.js +94 -0
  16. package/build/tools/addIssueComment.js +44 -0
  17. package/build/tools/addProject.js +39 -0
  18. package/build/tools/addPullRequest.js +65 -0
  19. package/build/tools/addPullRequestComment.js +52 -0
  20. package/build/tools/addWiki.js +29 -0
  21. package/build/tools/countIssues.js +111 -0
  22. package/build/tools/deleteIssue.js +29 -0
  23. package/build/tools/deleteProject.js +29 -0
  24. package/build/tools/downloadDocumentAttachment.js +1 -0
  25. package/build/tools/dynamicTools/toolsets.js +103 -0
  26. package/build/tools/getCategories.js +30 -0
  27. package/build/tools/getCustomFields.js +37 -0
  28. package/build/tools/getDocument.js +20 -0
  29. package/build/tools/getDocumentTree.js +20 -0
  30. package/build/tools/getDocuments.js +25 -0
  31. package/build/tools/getGitRepositories.js +29 -0
  32. package/build/tools/getGitRepository.js +41 -0
  33. package/build/tools/getIssue.js +29 -0
  34. package/build/tools/getIssueComments.js +45 -0
  35. package/build/tools/getIssueTypes.js +30 -0
  36. package/build/tools/getIssues.js +155 -0
  37. package/build/tools/getMyself.js +14 -0
  38. package/build/tools/getNotifications.js +35 -0
  39. package/build/tools/getNotificationsCount.js +20 -0
  40. package/build/tools/getPriorities.js +13 -0
  41. package/build/tools/getProject.js +29 -0
  42. package/build/tools/getProjectList.js +23 -0
  43. package/build/tools/getPullRequest.js +44 -0
  44. package/build/tools/getPullRequestComments.js +60 -0
  45. package/build/tools/getPullRequests.js +65 -0
  46. package/build/tools/getPullRequestsCount.js +57 -0
  47. package/build/tools/getResolutions.js +13 -0
  48. package/build/tools/getSpace.js +14 -0
  49. package/build/tools/getUsers.js +14 -0
  50. package/build/tools/getWatchingListCount.js +17 -0
  51. package/build/tools/getWatchingListItems.js +17 -0
  52. package/build/tools/getWiki.js +21 -0
  53. package/build/tools/getWikiPages.js +37 -0
  54. package/build/tools/getWikisCount.js +29 -0
  55. package/build/tools/markNotificationAsRead.js +26 -0
  56. package/build/tools/resetUnreadNotificationCount.js +13 -0
  57. package/build/tools/tools.js +143 -0
  58. package/build/tools/updateIssue.js +116 -0
  59. package/build/tools/updateProject.js +57 -0
  60. package/build/tools/updatePullRequest.js +68 -0
  61. package/build/tools/updatePullRequestComment.js +51 -0
  62. package/build/types/mcp.js +1 -0
  63. package/build/types/result.js +3 -0
  64. package/build/types/tool.js +1 -0
  65. package/build/types/toolsets.js +1 -0
  66. package/build/types/zod/backlogOutputDefinition.js +468 -0
  67. package/build/utils/generateFieldsDescription.js +47 -0
  68. package/build/utils/resolveIdOrKey.js +25 -0
  69. package/build/utils/runToolSafely.js +18 -0
  70. package/build/utils/tokenCounter.js +11 -0
  71. package/build/utils/toolRegistrar.js +12 -0
  72. package/build/utils/toolsetUtils.js +48 -0
  73. package/build/utils/wrapServerWithToolRegistry.js +16 -0
  74. package/build/version.js +1 -0
  75. package/build/version.template.js +1 -0
  76. package/package.json +52 -0
package/README.md ADDED
@@ -0,0 +1,501 @@
1
+ # Backlog MCP Server
2
+
3
+ ![MIT License](https://img.shields.io/badge/license-MIT-green.svg)
4
+ ![Build](https://github.com/nulab/backlog-mcp-server/actions/workflows/ci.yml/badge.svg)
5
+ ![Last Commit](https://img.shields.io/github/last-commit/nulab/backlog-mcp-server.svg)
6
+
7
+ [📘 日本語でのご利用ガイド](./README.ja.md)
8
+
9
+ A Model Context Protocol (MCP) server for interacting with the Backlog API. This server provides tools for managing projects, issues, wiki pages, and more in Backlog through AI agents like Claude Desktop / Cline / Cursor etc.
10
+
11
+ ## Features
12
+
13
+ - Project tools (create, read, update, delete)
14
+ - Issue tracking and comments (create, update, delete, list)
15
+ - Wiki page support
16
+ - Git repository and pull request tools
17
+ - Notification tools
18
+ - GraphQL-style field selection for optimized responses
19
+ - Token limiting for large responses
20
+
21
+ ## Getting Started
22
+
23
+ ### Requirements
24
+
25
+ - Docker
26
+ - A Backlog account with API access
27
+ - API key from your Backlog account
28
+
29
+ ### Option 1: Install via Docker
30
+
31
+ The easiest way to use this MCP server is through MCP configurations:
32
+
33
+ 1. Open MCP settings
34
+ 2. Navigate to the MCP configuration section
35
+ 3. Add the following configuration:
36
+
37
+ ```json
38
+ {
39
+ "mcpServers": {
40
+ "backlog": {
41
+ "command": "docker",
42
+ "args": [
43
+ "run",
44
+ "--pull", "always",
45
+ "-i",
46
+ "--rm",
47
+ "-e", "BACKLOG_DOMAIN",
48
+ "-e", "BACKLOG_API_KEY",
49
+ "ghcr.io/nulab/backlog-mcp-server"
50
+ ],
51
+ "env": {
52
+ "BACKLOG_DOMAIN": "your-domain.backlog.com",
53
+ "BACKLOG_API_KEY": "your-api-key"
54
+ }
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ Replace `your-domain.backlog.com` with your Backlog domain and `your-api-key` with your Backlog API key.
61
+
62
+ ✅ If you cannot use --pull always, you can manually update the image using:
63
+
64
+ ```
65
+ docker pull ghcr.io/nulab/backlog-mcp-server:latest
66
+ ```
67
+
68
+ ### Option 2: Manual Setup (Node.js)
69
+
70
+ 1. Clone and install:
71
+ ```bash
72
+ git clone https://github.com/nulab/backlog-mcp-server.git
73
+ cd backlog-mcp-server
74
+ npm install
75
+ npm run build
76
+ ```
77
+
78
+ 2. Set your json to use as MCP
79
+ ```json
80
+ {
81
+ "mcpServers": {
82
+ "backlog": {
83
+ "command": "node",
84
+ "args": [
85
+ "your-repository-location/build/index.js"
86
+ ],
87
+ "env": {
88
+ "BACKLOG_DOMAIN": "your-domain.backlog.com",
89
+ "BACKLOG_API_KEY": "your-api-key"
90
+ }
91
+ }
92
+ }
93
+ }
94
+ ```
95
+
96
+ ## Tool Configuration
97
+
98
+ You can selectively enable or disable specific **toolsets** using the `--enable-toolsets` command-line flag or the `ENABLE_TOOLSETS` environment variable. This allows better control over which tools are available to the AI agent and helps reduce context size.
99
+
100
+ ### Available Toolsets
101
+
102
+ The following toolsets are available (enabled by default when `"all"` is used):
103
+
104
+ | Toolset | Description |
105
+ |-----------------|--------------------------------------------------------------------------------------|
106
+ | `space` | Tools for managing Backlog space settings and general information |
107
+ | `project` | Tools for managing projects, categories, custom fields, and issue types |
108
+ | `issue` | Tools for managing issues and their comments |
109
+ | `wiki` | Tools for managing wiki pages |
110
+ | `git` | Tools for managing Git repositories and pull requests |
111
+ | `notifications` | Tools for managing user notifications |
112
+ | `document` | Tools for viewing documents and document trees |
113
+
114
+ ### Specifying Toolsets
115
+
116
+ You can control toolset activation in the following ways:
117
+
118
+ Using via CLI:
119
+
120
+ ```bash
121
+ --enable-toolsets space,project,issue
122
+ ```
123
+
124
+ Or via environment variable:
125
+
126
+ ```
127
+ ENABLE_TOOLSETS="space,project,issue"
128
+ ```
129
+
130
+ If all is specified, all available toolsets will be enabled. This is also the default behavior.
131
+
132
+ Using selective toolsets can be helpful if the toolset list is too large for your AI agent or if certain tools are causing performance issues. In such cases, disabling unused toolsets may improve stability.
133
+
134
+ > 🧩 Tip: `project` toolset is highly recommended, as many other tools rely on project data as an entry point.
135
+
136
+ ### Dynamic Toolset Discovery (Experimental)
137
+
138
+ If you're using the MCP server with AI agents, you can enable dynamic discovery of toolsets at runtime:
139
+
140
+ Enabling via CLI:
141
+
142
+ ```
143
+ --dynamic-toolsets
144
+ ```
145
+
146
+ Or via environment variable::
147
+
148
+ ```
149
+ -e DYNAMIC_TOOLSETS=1 \
150
+ ```
151
+
152
+ With dynamic toolsets enabled, the LLM will be able to list and activate toolsets on demand via tool interface.
153
+
154
+ ## Available Tools
155
+
156
+ ### Toolset: `space`
157
+ Tools for managing Backlog space settings and general information.
158
+ - `get_space`: Returns information about the Backlog space.
159
+ - `get_users`: Returns list of users in the Backlog space.
160
+ - `get_myself`: Returns information about the authenticated user.
161
+
162
+ ### Toolset: `project`
163
+ Tools for managing projects, categories, custom fields, and issue types.
164
+ - `get_project_list`: Returns list of projects.
165
+ - `add_project`: Creates a new project.
166
+ - `get_project`: Returns information about a specific project.
167
+ - `update_project`: Updates an existing project.
168
+ - `delete_project`: Deletes a project.
169
+
170
+ ### Toolset: `issue`
171
+ Tools for managing issues, their comments, and related items like priorities, categories, custom fields, issue types, resolutions, and watching lists.
172
+ - `get_issue`: Returns information about a specific issue.
173
+ - `get_issues`: Returns list of issues.
174
+ - `count_issues`: Returns count of issues.
175
+ - `add_issue`: Creates a new issue in the specified project.
176
+ - `update_issue`: Updates an existing issue.
177
+ - `delete_issue`: Deletes an issue.
178
+ - `get_issue_comments`: Returns list of comments for an issue.
179
+ - `add_issue_comment`: Adds a comment to an issue.
180
+ - `get_priorities`: Returns list of priorities.
181
+ - `get_categories`: Returns list of categories for a project.
182
+ - `get_custom_fields`: Returns list of custom fields for a project.
183
+ - `get_issue_types`: Returns list of issue types for a project.
184
+ - `get_resolutions`: Returns list of issue resolutions.
185
+ - `get_watching_list_items`: Returns list of watching items for a user.
186
+ - `get_watching_list_count`: Returns count of watching items for a user.
187
+
188
+ ### Toolset: `wiki`
189
+ Tools for managing wiki pages.
190
+ - `get_wiki_pages`: Returns list of Wiki pages.
191
+ - `get_wikis_count`: Returns count of wiki pages in a project.
192
+ - `get_wiki`: Returns information about a specific wiki page.
193
+ - `add_wiki`: Creates a new wiki page.
194
+
195
+ ### Toolset: `git`
196
+ Tools for managing Git repositories and pull requests.
197
+ - `get_git_repositories`: Returns list of Git repositories for a project.
198
+ - `get_git_repository`: Returns information about a specific Git repository.
199
+ - `get_pull_requests`: Returns list of pull requests for a repository.
200
+ - `get_pull_requests_count`: Returns count of pull requests for a repository.
201
+ - `get_pull_request`: Returns information about a specific pull request.
202
+ - `add_pull_request`: Creates a new pull request.
203
+ - `update_pull_request`: Updates an existing pull request.
204
+ - `get_pull_request_comments`: Returns list of comments for a pull request.
205
+ - `add_pull_request_comment`: Adds a comment to a pull request.
206
+ - `update_pull_request_comment`: Updates a comment on a pull request.
207
+
208
+ ### Toolset: `notifications`
209
+ Tools for managing user notifications.
210
+ - `get_notifications`: Returns list of notifications.
211
+ - `get_notifications_count`: Returns count of notifications.
212
+ - `reset_unread_notification_count`: Resets unread notification count.
213
+ - `mark_notification_as_read`: Marks a notification as read.
214
+
215
+ ### Toolset: `document`
216
+ Tools for managing documents and document trees in Backlog projects.
217
+ - `get_document_tree`: Returns the hierarchical tree of documents for a project, including folders and ne
218
+ - `get_documents`: Returns a flat list of documents in a project or folder.
219
+ - `get_document`: Returns detailed information about a specific document, including metadata, content, an
220
+
221
+ ## Usage Examples
222
+
223
+ Once the MCP server is configured in AI agents, you can use the tools directly in your conversations. Here are some examples:
224
+
225
+ - Listing Projects
226
+ ```
227
+ Could you list all my Backlog projects?
228
+ ```
229
+ - Creating a New Issue
230
+ ```
231
+ Create a new bug issue in the PROJECT-KEY project with high priority titled "Fix login page error"
232
+ ```
233
+ - Getting Project Details
234
+ ```
235
+ Show me the details of the PROJECT-KEY project
236
+ ```
237
+ - Working with Git Repositories
238
+ ```
239
+ List all Git repositories in the PROJECT-KEY project
240
+ ```
241
+ - Managing Pull Requests
242
+ ```
243
+ Show me all open pull requests in the repository "repo-name" of PROJECT-KEY project
244
+ ```
245
+ ```
246
+ Create a new pull request from branch "feature/new-feature" to "main" in the repository "repo-name" of PROJECT-KEY project
247
+ ```
248
+ - Watching Items
249
+ ```
250
+ Show me all items I'm watching
251
+ ```
252
+
253
+ ### i18n / Overriding Descriptions
254
+
255
+ You can override the descriptions of tools by creating a `.backlog-mcp-serverrc.json` file in your **home directory**.
256
+
257
+ The file should contain a JSON object with the tool names as keys and the new descriptions as values.
258
+ For example:
259
+
260
+ ```json
261
+ {
262
+ "TOOL_ADD_ISSUE_COMMENT_DESCRIPTION": "An alternative description",
263
+ "TOOL_CREATE_PROJECT_DESCRIPTION": "Create a new project in Backlog"
264
+ }
265
+ ```
266
+
267
+ When the server starts, it determines the final description for each tool based on the following priority:
268
+
269
+ 1. Environment variables (e.g., `BACKLOG_MCP_TOOL_ADD_ISSUE_COMMENT_DESCRIPTION`)
270
+ 2. Entries in `.backlog-mcp-serverrc.json` - Supported configuration file formats: .json, .yaml, .yml
271
+ 3. Built-in fallback values (English)
272
+
273
+ Sample config:
274
+
275
+ ```json
276
+ {
277
+ "mcpServers": {
278
+ "backlog": {
279
+ "command": "docker",
280
+ "args": [
281
+ "run",
282
+ "-i",
283
+ "--rm",
284
+ "-e", "BACKLOG_DOMAIN",
285
+ "-e", "BACKLOG_API_KEY",
286
+ "-v", "/yourcurrentdir/.backlog-mcp-serverrc.json:/root/.backlog-mcp-serverrc.json:ro",
287
+ "ghcr.io/nulab/backlog-mcp-server"
288
+ ],
289
+ "env": {
290
+ "BACKLOG_DOMAIN": "your-domain.backlog.com",
291
+ "BACKLOG_API_KEY": "your-api-key"
292
+ }
293
+ }
294
+ }
295
+ }
296
+ ```
297
+
298
+ ### Exporting Current Translations
299
+
300
+ You can export the current default translations (including any overrides) by running the binary with the --export-translations flag.
301
+
302
+ This will print all tool descriptions to stdout, including any customizations you have made.
303
+
304
+ Example:
305
+
306
+ ```bash
307
+ docker run -i --rm ghcr.io/nulab/backlog-mcp-server node build/index.js --export-translations
308
+ ```
309
+
310
+ or
311
+
312
+ ```bash
313
+ npx github:nulab/backlog-mcp-server --export-translations
314
+ ```
315
+
316
+ ### Using a Japanese Translation Template
317
+ A sample Japanese configuration file is provided at:
318
+
319
+ ```bash
320
+ translationConfig/.backlog-mcp-serverrc.json.example
321
+ ```
322
+
323
+ To use it, copy it to your home directory as .backlog-mcp-serverrc.json:
324
+
325
+ You can then edit the file to customize the descriptions as needed.
326
+
327
+ ### Using Environment Variables
328
+ Alternatively, you can override tool descriptions via environment variables.
329
+
330
+ The environment variable names are based on the tool keys, prefixed with BACKLOG_MCP_ and written in uppercase.
331
+
332
+ Example:
333
+ To override the TOOL_ADD_ISSUE_COMMENT_DESCRIPTION:
334
+
335
+ ```json
336
+ {
337
+ "mcpServers": {
338
+ "backlog": {
339
+ "command": "docker",
340
+ "args": [
341
+ "run",
342
+ "-i",
343
+ "--rm",
344
+ "-e", "BACKLOG_DOMAIN",
345
+ "-e", "BACKLOG_API_KEY",
346
+ "-e", "BACKLOG_MCP_TOOL_ADD_ISSUE_COMMENT_DESCRIPTION"
347
+ "ghcr.io/nulab/backlog-mcp-server"
348
+ ],
349
+ "env": {
350
+ "BACKLOG_DOMAIN": "your-domain.backlog.com",
351
+ "BACKLOG_API_KEY": "your-api-key",
352
+ "BACKLOG_MCP_TOOL_ADD_ISSUE_COMMENT_DESCRIPTION": "An alternative description"
353
+ }
354
+ }
355
+ }
356
+ }
357
+ ```
358
+
359
+ The server loads the config file synchronously at startup.
360
+
361
+ Environment variables always take precedence over the config file.
362
+
363
+ ## Advanced Features
364
+
365
+ ### Tool Name Prefixing
366
+
367
+ Add prefix to tool names with:
368
+
369
+ ```
370
+ --prefix backlog_
371
+ ```
372
+
373
+ or via environment variable:
374
+
375
+ ```
376
+ PREFIX="backlog_"
377
+ ```
378
+
379
+ This is especially useful if you're using multiple MCP servers or tools in the same environment and want to avoid name collisions. For example, get_project can become backlog_get_project to distinguish it from similarly named tools provided by other services.
380
+
381
+ ### Response Optimization & Token Limits
382
+
383
+ #### Field Selection (GraphQL-style)
384
+
385
+ ```
386
+ --optimize-response
387
+ ```
388
+
389
+ Or environment variable:
390
+
391
+ ```
392
+ OPTIMIZE_RESPONSE=1
393
+ ```
394
+
395
+ Then, request only specific fields:
396
+
397
+ ```
398
+ get_project(projectIdOrKey: "PROJECT-KEY", fields: "{ name key description }")
399
+ ```
400
+
401
+ The AI will use field selection to optimize the response:
402
+
403
+ ```
404
+ get_project(projectIdOrKey: "PROJECT-KEY", fields: "{ name key description }")
405
+ ```
406
+
407
+ Benefits:
408
+ - Reduce response size by requesting only needed fields
409
+ - Focus on specific data points
410
+ - Improve performance for large responses
411
+
412
+ #### Token Limiting
413
+
414
+ Large responses are automatically limited to prevent exceeding token limits:
415
+ - Default limit: 50,000 tokens
416
+ - Configurable via `MAX_TOKENS` environment variable
417
+ - Responses exceeding the limit are truncated with a message
418
+
419
+ You can change this using:
420
+
421
+ ```
422
+ MAX_TOKENS=10000
423
+ ```
424
+
425
+ If a response exceeds the limit, it will be truncated with a warning.
426
+ > Note: This is a best-effort mitigation, not a guaranteed enforcement.
427
+
428
+ ### Full Custom Configuration Example
429
+
430
+ This section demonstrates advanced configuration using multiple environment variables. These are experimental features and may not be supported across all MCP clients. This is not part of the MCP standard specification and should be used with caution.
431
+
432
+ ```json
433
+ {
434
+ "mcpServers": {
435
+ "backlog": {
436
+ "command": "docker",
437
+ "args": [
438
+ "run",
439
+ "-i",
440
+ "--rm",
441
+ "-e", "BACKLOG_DOMAIN",
442
+ "-e", "BACKLOG_API_KEY",
443
+ "-e", "MAX_TOKENS",
444
+ "-e", "OPTIMIZE_RESPONSE",
445
+ "-e", "PREFIX",
446
+ "-e", "ENABLE_TOOLSETS",
447
+ "ghcr.io/nulab/backlog-mcp-server"
448
+ ],
449
+ "env": {
450
+ "BACKLOG_DOMAIN": "your-domain.backlog.com",
451
+ "BACKLOG_API_KEY": "your-api-key",
452
+ "MAX_TOKENS": "10000",
453
+ "OPTIMIZE_RESPONSE": "1",
454
+ "PREFIX": "backlog_",
455
+ "ENABLE_TOOLSETS": "space,project,issue",
456
+ "ENABLE_DYNAMIC_TOOLSETS": "1"
457
+ }
458
+ }
459
+ }
460
+ }
461
+ ```
462
+
463
+ ## Development
464
+
465
+ ### Running Tests
466
+
467
+ ```bash
468
+ npm test
469
+ ```
470
+
471
+ ### Adding New Tools
472
+
473
+ 1. Create a new file in `src/tools/` following the pattern of existing tools
474
+ 2. Create a corresponding test file
475
+ 3. Add the new tool to `src/tools/tools.ts`
476
+ 4. Build and test your changes
477
+
478
+ ### Command Line Options
479
+
480
+ The server supports several command line options:
481
+
482
+ - `--export-translations`: Export all translation keys and values
483
+ - `--optimize-response`: Enable GraphQL-style field selection
484
+ - `--max-tokens=NUMBER`: Set maximum token limit for responses
485
+ - `--prefix=STRING`: Optional string prefix to prepend to all tool names (default: "")
486
+ - `--enable-toolsets <toolsets...>`: Specify which toolsets to enable (comma-separated or multiple arguments). Defaults to "all".
487
+ Example: `--enable-toolsets space,project` or `--enable-toolsets issue --enable-toolsets git`
488
+ Available toolsets: `space`, `project`, `issue`, `wiki`, `git`, `notifications`.
489
+
490
+ Example:
491
+ ```bash
492
+ node build/index.js --optimize-response --max-tokens=100000 --prefix="backlog_" --enable-toolsets space,issue
493
+ ```
494
+
495
+ ## License
496
+
497
+ This project is licensed under the [MIT License](./LICENSE).
498
+
499
+ Please note: This tool is provided under the MIT License **without any warranty or official support**.
500
+ Use it at your own risk after reviewing the contents and determining its suitability for your needs.
501
+ If you encounter any issues, please report them via [GitHub Issues](../../issues).
@@ -0,0 +1,8 @@
1
+ import { parseBacklogAPIError } from './parseBacklogAPIError.js';
2
+ export const backlogErrorHandler = (err) => {
3
+ const parsed = parseBacklogAPIError(err);
4
+ return {
5
+ kind: 'error',
6
+ message: parsed.message,
7
+ };
8
+ };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Converts Backlog-style customFields array into proper payload format
3
+ */
4
+ export function customFieldsToPayload(customFields) {
5
+ if (customFields == null) {
6
+ return {};
7
+ }
8
+ const result = {};
9
+ for (const field of customFields) {
10
+ result[`customField_${field.id}`] = field.value;
11
+ if (field.otherValue) {
12
+ result[`customField_${field.id}_otherValue`] = field.otherValue;
13
+ }
14
+ }
15
+ return result;
16
+ }
@@ -0,0 +1,38 @@
1
+ export function parseBacklogAPIError(err) {
2
+ const e = err;
3
+ if (e._name && e._status && e._url) {
4
+ const status = e._status;
5
+ const url = e._url;
6
+ const code = e._body?.errors?.[0]?.code;
7
+ const message = e._body?.errors?.[0]?.message ?? 'An unknown error occurred.';
8
+ if (e._name === 'BacklogAuthError') {
9
+ return {
10
+ type: 'BacklogAuthError',
11
+ message: `Authentication failed (HTTP ${status}). Please check your API key or permissions.`,
12
+ status,
13
+ url,
14
+ };
15
+ }
16
+ if (e._name === 'BacklogApiError') {
17
+ return {
18
+ type: 'BacklogApiError',
19
+ message: `Backlog API error (code: ${code}, status: ${status})\n${message}`,
20
+ status,
21
+ code,
22
+ url,
23
+ };
24
+ }
25
+ if (e._name === 'UnexpectedError') {
26
+ return {
27
+ type: 'UnexpectedError',
28
+ message: `Unexpected error (HTTP ${status}) while accessing ${url}.`,
29
+ status,
30
+ url,
31
+ };
32
+ }
33
+ }
34
+ return {
35
+ type: 'UnknownError',
36
+ message: err?.message ?? 'An unknown error occurred.',
37
+ };
38
+ }
@@ -0,0 +1,28 @@
1
+ import { cosmiconfigSync } from 'cosmiconfig';
2
+ import os from 'os';
3
+ export function createTranslationHelper(options) {
4
+ const usedKeys = {};
5
+ const configName = options?.configName ?? 'backlog-mcp-server';
6
+ // Load config file
7
+ const explorer = cosmiconfigSync(configName);
8
+ const searchPath = options?.searchDir ?? os.homedir();
9
+ const configResult = explorer.search(searchPath);
10
+ const config = configResult?.config || {};
11
+ function toEnvKey(key) {
12
+ return `BACKLOG_MCP_${key}`;
13
+ }
14
+ function t(key, fallback) {
15
+ const upperKey = key.toUpperCase();
16
+ if (usedKeys[upperKey]) {
17
+ return usedKeys[upperKey];
18
+ }
19
+ // Priority:ENV → config → fallback
20
+ const value = process.env[toEnvKey(upperKey)] || config[upperKey] || fallback;
21
+ usedKeys[upperKey] = value;
22
+ return value;
23
+ }
24
+ function dump() {
25
+ return { ...usedKeys };
26
+ }
27
+ return { t, dump };
28
+ }
@@ -0,0 +1,26 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { wrapWithErrorHandling } from '../transformers/wrapWithErrorHandling.js';
3
+ import { wrapWithFieldPicking } from '../transformers/wrapWithFieldPicking.js';
4
+ import { wrapWithTokenLimit } from '../transformers/wrapWithTokenLimit.js';
5
+ import { wrapWithToolResult } from '../transformers/wrapWithToolResult.js';
6
+ import { z } from 'zod';
7
+ import { generateFieldsDescription } from '../../utils/generateFieldsDescription.js';
8
+ export function composeToolHandler(tool, options) {
9
+ const { useFields, errorHandler, maxTokens } = options;
10
+ // Step 1: Add `fields` to schema if needed
11
+ if (useFields) {
12
+ const fieldDesc = generateFieldsDescription(tool.outputSchema, tool.importantFields ?? [], tool.name);
13
+ tool.schema = extendSchema(tool.schema, fieldDesc);
14
+ }
15
+ // Step 2: Compose
16
+ let handler = wrapWithErrorHandling(tool.handler, errorHandler);
17
+ if (useFields) {
18
+ handler = wrapWithFieldPicking(handler);
19
+ }
20
+ return wrapWithToolResult(wrapWithTokenLimit(handler, maxTokens));
21
+ }
22
+ function extendSchema(schema, desc) {
23
+ return schema.extend({
24
+ fields: z.string().describe(desc),
25
+ });
26
+ }
@@ -0,0 +1,4 @@
1
+ import { runToolSafely } from '../../utils/runToolSafely.js';
2
+ export function wrapWithErrorHandling(fn, onError) {
3
+ return runToolSafely(fn, onError);
4
+ }
@@ -0,0 +1,55 @@
1
+ import { parse } from 'graphql';
2
+ import { isErrorLike } from '../../types/result.js';
3
+ export function wrapWithFieldPicking(fn) {
4
+ return async (input) => {
5
+ const { fields, ...rest } = input;
6
+ const result = await fn(rest);
7
+ if (!fields || isErrorLike(result)) {
8
+ return result;
9
+ }
10
+ const selectionSet = parseFieldsSelection(fields);
11
+ const resultData = result.data;
12
+ if (Array.isArray(resultData)) {
13
+ return {
14
+ kind: 'ok',
15
+ data: resultData.map((item) => pickFieldsFromData(item, selectionSet)),
16
+ };
17
+ }
18
+ else if (typeof result === 'object' && result !== null) {
19
+ return {
20
+ kind: 'ok',
21
+ data: pickFieldsFromData(resultData, selectionSet),
22
+ };
23
+ }
24
+ else {
25
+ return result;
26
+ }
27
+ };
28
+ }
29
+ function parseFieldsSelection(fieldsString) {
30
+ const query = `query Dummy ${fieldsString}`;
31
+ const ast = parse(query);
32
+ const opDef = ast.definitions[0];
33
+ if (opDef.kind !== 'OperationDefinition' || !opDef.selectionSet) {
34
+ throw new Error('Invalid GraphQL fields');
35
+ }
36
+ return opDef.selectionSet;
37
+ }
38
+ function pickFieldsFromData(data, selectionSet) {
39
+ const result = {};
40
+ for (const selection of selectionSet.selections) {
41
+ if (selection.kind === 'Field') {
42
+ const key = selection.name.value;
43
+ if (data != null && key in data) {
44
+ const value = data[key];
45
+ if (selection.selectionSet && value != null) {
46
+ result[key] = pickFieldsFromData(data[key], selection.selectionSet);
47
+ }
48
+ else {
49
+ result[key] = data[key];
50
+ }
51
+ }
52
+ }
53
+ }
54
+ return result;
55
+ }