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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -479,12 +479,31 @@ MAX_TOKENS=10000

> 注:これはベストエフォートの緩和策であり、保証された強制ではありません。

### 添付ファイルのアップロード

`add_attachment` は、サーバーが動いているマシンのファイルを読む唯一のツールです。`filePath` で指定したファイルをスペースにアップロードし、`{ id, name, size }` を返します。この id を `add_issue`、`update_issue`、`add_issue_comment` の `attachmentId` に渡すと、ファイルが添付されます(これらのツールは、アップロード済みのファイルを添付するだけで、自分ではアップロードしません)。

パスは、クライアントではなく **サーバーが動いているマシン上** で解決されます。

- stdio / npx で使う場合は同じマシンなので、ローカルのパスをそのまま書けます。
- コンテナイメージで使う場合は別のマシン扱いです。先にディレクトリをバインドマウントし(`-v /host/dir:/data`)、コンテナ内のパスを渡してください。

| 変数 | 説明 |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BACKLOG_ATTACHMENT_ROOTS` | `add_attachment` が読んでよいディレクトリ。OS のパス区切り文字(Unix は `:`、Windows は `;`)で区切ります。stdio では、未設定なら制限なしです。HTTP では、設定するまで `add_attachment` はすべてのアップロードを拒否します(設定しないと、リモートの利用者がサーバーの読めるファイルを何でも読めてしまうため)。 |

チェックの前にシンボリックリンクを解決するので、許可したディレクトリ内のリンクを使って、外のファイルを読むことはできません。

```
BACKLOG_ATTACHMENT_ROOTS=/srv/uploads:/tmp/backlog-in
```

### ログ出力

ログは **stderr** に出力されます(stdio トランスポートでは stdout が JSON-RPC のストリームに使われるため)。

| 変数 | 説明 |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 変数 | 説明 |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LOG_LEVEL` | `fatal` / `error` / `warn` / `info` / `debug` / `trace` / `silent`。既定は `NODE_ENV` が `production`(未設定時もこれに含まれる)のとき `error`、それ以外は `debug`。認識できない値は通知した上で既定値にフォールバックします。 |

出力**フォーマット**は引き続き `NODE_ENV` が決めます(`production` 以外では `pino-pretty` が利用可能なら人間向けの整形出力に切り替わります)。ログ量を変えたいときは `NODE_ENV` ではなく `LOG_LEVEL` を設定してください。デプロイ先で構造化 JSON のまま保てます。
Expand Down
28 changes: 24 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ Tools for managing Backlog space settings and general information.
- `get_space`: Returns information about the Backlog space.
- `get_users`: Returns list of users in the Backlog space.
- `get_myself`: Returns information about the authenticated user.
- `add_attachment`: Uploads a file and returns its attachment id, for use in the `attachmentId` array of `add_issue`, `update_issue` or `add_issue_comment`. See [Attachment uploads](#attachment-uploads).

### Toolset: `project`

Expand Down Expand Up @@ -543,7 +544,7 @@ This is especially useful if you're using multiple MCP servers or tools in the s

Tool results are compacted before they are returned. This is always on, and applies to every tool except `get_issue_attachment`, which returns the file itself:

- A user nested in a result (`createdUser`, `assignee`, `stars[].presenter`, a notification's `sender`, …) is reduced to `id`, `userId` and `name`. A user that *is* the result — `get_myself`, the items of `get_users` or `get_project_users` — is returned whole.
- A user nested in a result (`createdUser`, `assignee`, `stars[].presenter`, a notification's `sender`, …) is reduced to `id`, `userId` and `name`. A user that _is_ the result — `get_myself`, the items of `get_users` or `get_project_users` — is returned whole.
- A nested project (each activity's and notification's `project`) is reduced to `id`, `projectKey` and `name`, and a nested issue (a pull request's or notification's `issue`) to `id`, `issueKey`, `summary` and `status`. A project or issue that is the result — `get_project`, `get_issue`, the items of `get_project_list` or `get_issues` — is returned whole, and so is the issue of each item of `get_watching_list_items`.
- Nested entities (statuses, issue types, categories, milestones, custom field items, …) omit `color` and `displayOrder`, and nested milestones also omit `description`. Tools that list these themselves (`get_issue_types`, `get_categories`, `get_version_milestone_list`, …) return them whole.
- Fields that are `null`, an empty string or an empty array are omitted. `0`, `false` and `{}` are kept. This also applies to a field named in `fields`: an empty one is left out rather than returned as empty.
Expand Down Expand Up @@ -598,15 +599,34 @@ If a response exceeds the limit, it will be truncated with a warning.

> Note: This is a best-effort mitigation, not a guaranteed enforcement.

### Attachment uploads

`add_attachment` is the only tool that reads the host's filesystem. It takes a `filePath`, uploads that file to the space and returns `{ id, name, size }`; the id is what `add_issue`, `update_issue` and `add_issue_comment` accept in `attachmentId`, since those tools attach existing uploads rather than performing one.

The path is resolved **on the machine running the server**, not on the client:

- With the stdio/npx setup the two are the same machine, so a local path works as written.
- In the container image they are not. Bind-mount the directory first (`-v /host/dir:/data`) and pass the path inside the container.

| Variable | Description |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `BACKLOG_ATTACHMENT_ROOTS` | Directories `add_attachment` may read from, separated by the platform's path delimiter (`:` on Unix, `;` on Windows). Unset means no restriction over stdio; over HTTP, `add_attachment` refuses every upload until this is set, because remote callers would otherwise read any file the server can. |

Symlinks are resolved before the check, so a link inside an allowed directory cannot be used to reach a file outside it.

```
BACKLOG_ATTACHMENT_ROOTS=/srv/uploads:/tmp/backlog-in
```

### Logging

The server logs to **stderr** (stdout carries the JSON-RPC stream on the stdio transport).

| Variable | Description |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Variable | Description |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LOG_LEVEL` | `fatal`, `error`, `warn`, `info`, `debug`, `trace` or `silent`. Defaults to `error` when `NODE_ENV` is `production` — which is also the default when `NODE_ENV` is unset — and to `debug` otherwise. An unrecognised value is reported and the default is used. |

`NODE_ENV` still selects the output *format*: any value other than `production` switches to human-readable `pino-pretty` output when that package is available. Use `LOG_LEVEL`, not `NODE_ENV`, to change how much is logged, so that a deployment keeps structured JSON:
`NODE_ENV` still selects the output _format_: any value other than `production` switches to human-readable `pino-pretty` output when that package is available. Use `LOG_LEVEL`, not `NODE_ENV`, to change how much is logged, so that a deployment keeps structured JSON:

`pino-pretty` is a development dependency, so neither the published npm package nor the container image carries a copy. In those, logs are structured JSON whatever `NODE_ENV` says, and `LOG_LEVEL` is the only setting that changes the output.

Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ const mcpOption = {
const sharedToolsetGroup = buildToolsetGroup(
backlog,
descriptionHelper,
enabledToolsets
enabledToolsets,
{ attachmentRootsRequired: argv.transport !== 'stdio' }
);

reportUnknownOverrideKeys({
Expand Down
213 changes: 213 additions & 0 deletions src/tools/addAttachment.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { delimiter, join } from 'node:path';
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vite-plus/test';
import { postSpaceAttachment } from 'backlog-js';
import type { Client } from 'backlog-js';
import { addAttachmentTool } from './addAttachment.js';
import { createDescriptionHelper } from '../createDescriptionHelper.js';
import { ATTACHMENT_ROOTS_ENV } from '../utils/attachmentRoots.js';

vi.mock('backlog-js', async (importOriginal) => ({
...(await importOriginal<typeof import('backlog-js')>()),
postSpaceAttachment: vi.fn(),
}));

const FILE_CONTENT = 'screenshot bytes';

// A real temp tree rather than a mocked `node:fs`. The parts worth testing here
// are symlink resolution and the containment check, and both are properties of
// the filesystem: a mock that returned whatever the test asked for would assert
// only that the code calls the functions it obviously calls.
describe('addAttachmentTool', () => {
let root: string;
let allowed: string;
let outside: string;
let insideFile: string;
let outsideFile: string;

const mockPostSpaceAttachment = vi.mocked(postSpaceAttachment);
const mockClient = {} as Client;
const tool = addAttachmentTool(mockClient, createDescriptionHelper(), {
attachmentRootsRequired: false,
});
const remoteTool = addAttachmentTool(mockClient, createDescriptionHelper());

beforeAll(async () => {
root = await mkdtemp(join(tmpdir(), 'backlog-mcp-attachment-'));
allowed = join(root, 'allowed');
outside = join(root, 'outside');
await mkdir(allowed);
await mkdir(outside);

insideFile = join(allowed, 'evidence.png');
outsideFile = join(outside, 'secret.png');
await writeFile(insideFile, FILE_CONTENT);
await writeFile(outsideFile, FILE_CONTENT);
});

afterAll(async () => {
await rm(root, { recursive: true, force: true });
});

beforeEach(() => {
mockPostSpaceAttachment.mockReset();
mockPostSpaceAttachment.mockResolvedValue({
id: 42,
name: 'evidence.png',
size: 17,
} as Awaited<ReturnType<typeof postSpaceAttachment>>);
});

afterEach(() => {
vi.unstubAllEnvs();
});

it('uploads the file and returns what Backlog reports', async () => {
const result = await tool.handler({ filePath: insideFile });

expect(result).toEqual({ id: 42, name: 'evidence.png', size: 17 });
expect(mockPostSpaceAttachment).toHaveBeenCalledTimes(1);
});

it('sends the file under the `file` field, named after the basename', async () => {
await tool.handler({ filePath: insideFile });

const form = mockPostSpaceAttachment.mock.calls[0][1];
const sent = form.get('file');

expect(sent).toBeInstanceOf(Blob);
expect((sent as File).name).toBe('evidence.png');
expect(await (sent as Blob).text()).toBe(FILE_CONTENT);
});

it('reports a path it cannot read without saying why', async () => {
await expect(
tool.handler({ filePath: join(allowed, 'missing.png') })
).rejects.toThrow(/Cannot read file/);
expect(mockPostSpaceAttachment).not.toHaveBeenCalled();
});

it('refuses a directory', async () => {
await expect(tool.handler({ filePath: allowed })).rejects.toThrow(
/Not a regular file/
);
expect(mockPostSpaceAttachment).not.toHaveBeenCalled();
});

it('reads any path when no allowlist is configured', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, '');

await expect(
tool.handler({ filePath: outsideFile })
).resolves.toBeDefined();
});

it('refuses every path when roots are required but not configured', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, '');

await expect(remoteTool.handler({ filePath: insideFile })).rejects.toThrow(
new RegExp(`disabled: set ${ATTACHMENT_ROOTS_ENV}`)
);
expect(mockPostSpaceAttachment).not.toHaveBeenCalled();
});

it('uploads from a configured root when roots are required', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

await expect(
remoteTool.handler({ filePath: insideFile })
).resolves.toBeDefined();
});

it('accepts a file inside an allowed root', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

await expect(tool.handler({ filePath: insideFile })).resolves.toBeDefined();
});

it('refuses a file outside every allowed root', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

await expect(tool.handler({ filePath: outsideFile })).rejects.toThrow(
new RegExp(ATTACHMENT_ROOTS_ENV)
);
expect(mockPostSpaceAttachment).not.toHaveBeenCalled();
});

it('gives a missing file outside the roots the same error as an existing one', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

// If this said "Cannot read file" instead, the difference between the two
// messages would reveal which paths exist beyond the allowlist.
await expect(
tool.handler({ filePath: join(outside, 'does-not-exist.png') })
).rejects.toThrow(new RegExp(ATTACHMENT_ROOTS_ENV));
expect(mockPostSpaceAttachment).not.toHaveBeenCalled();
});

it('gives a directory outside the roots the same error as a file', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

await expect(tool.handler({ filePath: outside })).rejects.toThrow(
new RegExp(ATTACHMENT_ROOTS_ENV)
);
expect(mockPostSpaceAttachment).not.toHaveBeenCalled();
});

it('still reports a missing file inside the roots as unreadable', async () => {
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

await expect(
tool.handler({ filePath: join(allowed, 'does-not-exist.png') })
).rejects.toThrow(/Cannot read file/);
});

it('refuses a symlink that sits inside an allowed root but points outside it', async () => {
const link = join(allowed, 'link-to-secret.png');
await symlink(outsideFile, link);
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

try {
await expect(tool.handler({ filePath: link })).rejects.toThrow(
new RegExp(ATTACHMENT_ROOTS_ENV)
);
expect(mockPostSpaceAttachment).not.toHaveBeenCalled();
} finally {
await rm(link, { force: true });
}
});

it('keeps working when one configured root does not exist', async () => {
vi.stubEnv(
ATTACHMENT_ROOTS_ENV,
[join(root, 'no-such-dir'), allowed].join(delimiter)
);

await expect(tool.handler({ filePath: insideFile })).resolves.toBeDefined();
});
it('uploads a symlink under the name the caller used, not the target name', async () => {
const link = join(allowed, 'as-named-by-caller.png');
await symlink(insideFile, link);
vi.stubEnv(ATTACHMENT_ROOTS_ENV, allowed);

try {
await tool.handler({ filePath: link });

const sent = mockPostSpaceAttachment.mock.calls[0][1].get('file') as File;
expect(sent.name).toBe('as-named-by-caller.png');
expect(await sent.text()).toBe(FILE_CONTENT);
} finally {
await rm(link, { force: true });
}
});
});
Loading