diff --git a/apps/cli-docs/src/content/docs/contributing.md b/apps/cli-docs/src/content/docs/contributing.md index d615d0205f..339c7ce5d7 100644 --- a/apps/cli-docs/src/content/docs/contributing.md +++ b/apps/cli-docs/src/content/docs/contributing.md @@ -70,7 +70,7 @@ toolkit/ │ │ │ ├── event/ # analytics, list, send, view │ │ │ ├── feedback/ # list, resolve, spam, unresolve, view │ │ │ ├── integration/ # delete, list -│ │ │ ├── issue/ # archive, events, explain, link, list, merge, plan, resolve, tags, unlink, unresolve, view +│ │ │ ├── issue/ # archive, comment, comments, events, explain, link, list, merge, plan, resolve, tags, unlink, unresolve, view │ │ │ ├── local/ # close, create, list, reset, restart, retention, run, serve, start, status, stop, view │ │ │ ├── log/ # list, view │ │ │ ├── monitor/ # list, run diff --git a/packages/cli/lint-rules/cli-oxlint-plugin.js b/packages/cli/lint-rules/cli-oxlint-plugin.js index 9b71b5b070..1af27de1a4 100644 --- a/packages/cli/lint-rules/cli-oxlint-plugin.js +++ b/packages/cli/lint-rules/cli-oxlint-plugin.js @@ -497,6 +497,11 @@ const MANUAL_API_REQUEST_EXCEPTIONS = new Map([ "openSnapshotArchive", ], ], + // Issue comments are not in the public API schema. + [ + "lib/api/issue-comments.ts", + ["fetchIssueCommentPage", "createIssueComment"], + ], // Unauthenticated transport for the generated shared-issue call on another host. ["lib/api/issues.ts", ["getSharedIssue"]], // Unauthenticated transport for the generated handoff claim before login exists. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md index e06f1f3480..1527acd47b 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -462,6 +462,8 @@ Manage Sentry issues - `sentry issue list []` — List issues in a project - `sentry issue events ` — List events for a specific issue - `sentry issue tags ` — Show the top values of an issue tag +- `sentry issue comment ` — Comment on an issue, optionally attaching videos +- `sentry issue comments ` — List an issue's comments and their videos - `sentry issue explain ` — Analyze one or more issues using Seer AI - `sentry issue plan ` — Generate a solution plan using Seer AI - `sentry issue view ` — View details of one or more issues diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/issue.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/issue.md index a663a904e8..6b71ef1c05 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/issue.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/issue.md @@ -195,6 +195,82 @@ sentry issue tags FRONT-ABC browser.name --json sentry issue tags FRONT-ABC release --json --fields key,totalValues,topValues ``` +### `sentry issue comment ` + +Comment on an issue, optionally attaching videos + +**Arguments:** + +| Argument | Description | +|----------|-------------| +| `` | Issue: @latest, @most_frequent, <org>/ID, <org>/<project>#ID, <project>-suffix, ID, or suffix | +| `` | Comment text (Markdown) | + +**Flags:** +- `-a, --attach ... - Path of a video to attach (repeatable)` +- `-n, --dry-run - Show what would happen without making changes` + +**JSON Fields** (use `--json --fields` to select specific fields): + +| Field | Type | Description | +|-------|------|-------------| +| `id` | string | Comment ID; absent with --dry-run | +| `dateCreated` | string | When the comment was posted | +| `author` | string | Who posted the comment | +| `text` | string | Comment text, including links to attached videos | +| `attachments` | array | Videos attached to the comment | +| `dryRun` | boolean | True when --dry-run made no change | + +**Examples:** + +```bash +# Comment on an issue +sentry issue comment my-org/FRONT-ABC "Fixed in the next deploy" + +# Attach a screen recording of the bug +sentry issue comment FRONT-ABC "Repro steps below" --attach repro.mp4 + +# Check attachments without posting +sentry issue comment FRONT-ABC "Repro" --attach a.mp4 --attach b.webm --dry-run +``` + +### `sentry issue comments ` + +List an issue's comments and their videos + +**Arguments:** + +| Argument | Description | +|----------|-------------| +| `` | Issue: @latest, @most_frequent, <org>/ID, <org>/<project>#ID, <project>-suffix, ID, or suffix | + +**Flags:** +- `-d, --download - Directory to save attached videos into` + +**JSON Fields** (use `--json --fields` to select specific fields): + +| Field | Type | Description | +|-------|------|-------------| +| `id` | string | Comment ID; absent with --dry-run | +| `dateCreated` | string | When the comment was posted | +| `author` | string | Who posted the comment | +| `text` | string | Comment text, including links to attached videos | +| `attachments` | array | Videos attached to the comment | +| `dryRun` | boolean | True when --dry-run made no change | + +**Examples:** + +```bash +# Read the comments on an issue +sentry issue comments my-org/FRONT-ABC + +# Save the attached videos to ./videos +sentry issue comments FRONT-ABC --download ./videos + +# Get comments and video URLs as JSON +sentry issue comments FRONT-ABC --json --fields author,text,attachments +``` + ### `sentry issue explain ` Analyze one or more issues using Seer AI diff --git a/packages/cli/src/commands/issue/comments.ts b/packages/cli/src/commands/issue/comments.ts new file mode 100644 index 0000000000..8256d75948 --- /dev/null +++ b/packages/cli/src/commands/issue/comments.ts @@ -0,0 +1,261 @@ +/** + * sentry issue comment / sentry issue comments + * + * Post a comment on an issue, optionally with screen recordings attached, and + * read an issue's comments, optionally saving their videos to disk. + */ + +import { mkdir } from "node:fs/promises"; +import { basename, join } from "node:path"; +import { + commentAttachmentPath, + parseCommentAttachments, +} from "@sentry/mcp-core/comment-attachments"; +import type { SentryContext } from "../../context.js"; +import { + createIssueCommentWithVideos, + downloadIssueCommentAttachment, + type IssueComment, + listIssueComments, + readLocalVideo, +} from "../../lib/api-client.js"; +import { buildCommand } from "../../lib/command.js"; +import { + parseDirectoryPath, + parseFilePath, + parseText, +} from "../../lib/completion-target.js"; +import { + formatIssueComment, + formatIssueComments, +} from "../../lib/formatters/issue-comments.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; +import { DRY_RUN_ALIASES, DRY_RUN_FLAG } from "../../lib/mutate-command.js"; +import { withProgress } from "../../lib/polling.js"; +import { resolveOrgRegion } from "../../lib/region.js"; +import { IssueCommentOutputSchema } from "../../generated/output-schemas/issue.js"; +import type { IssueCommentOutput } from "../../output-schemas/issue.js"; +import { + type IssueTarget, + issueParameter, + issuePositional, +} from "./positional.js"; + +function commentAuthor(comment: IssueComment): string { + return ( + comment.user?.name || + comment.user?.email || + comment.sentry_app?.name || + "Sentry" + ); +} + +/** + * Comment output with each linked video's full API URL, built from the issue + * being read, the same URL `--download` fetches. + */ +function toOutput( + comment: IssueComment, + regionUrl: string, + org: string, + issueId: string, +): IssueCommentOutput { + const text = comment.data.text ?? ""; + const origin = regionUrl.replace(/\/$/, ""); + return { + id: comment.id, + dateCreated: comment.dateCreated, + author: commentAuthor(comment), + text, + attachments: parseCommentAttachments(text).map((link) => ({ + id: link.id, + name: link.name, + url: `${origin}${commentAttachmentPath(org, issueId, link.id)}`, + })), + }; +} + +type CommentFlags = { + readonly json: boolean; + readonly fields?: string[]; + readonly attach?: string[]; + readonly "dry-run": boolean; +}; + +export const commentCommand = buildCommand({ + docs: { + brief: "Comment on an issue, optionally attaching videos", + fullDescription: + "Post a comment to an issue's activity feed, visible to the whole team.\n\n" + + "Use --attach to upload screen recordings with the comment. Accepted\n" + + "formats are MP4, MOV, WebM and Ogg; the server's size limit applies\n" + + "(95 MB by default). Each video is linked after the comment text and\n" + + "plays inline in Sentry.\n\n" + + "Use --dry-run to check the files without uploading or posting anything.", + examples: [ + { + description: "Comment on an issue", + run: 'issue comment my-org/FRONT-ABC "Fixed in the next deploy"', + }, + { + description: "Attach a screen recording of the bug", + run: 'issue comment FRONT-ABC "Repro steps below" --attach repro.mp4', + }, + { + description: "Check attachments without posting", + run: 'issue comment FRONT-ABC "Repro" --attach a.mp4 --attach b.webm --dry-run', + }, + ], + }, + output: { + human: formatIssueComment, + schema: IssueCommentOutputSchema, + }, + parameters: { + positional: { + kind: "tuple", + parameters: [ + issueParameter({ command: "comment" }), + { + placeholder: "text", + brief: "Comment text (Markdown)", + parse: parseText, + }, + ], + }, + flags: { + attach: { + kind: "parsed", + parse: parseFilePath, + brief: "Path of a video to attach (repeatable)", + optional: true, + variadic: true, + }, + "dry-run": DRY_RUN_FLAG, + }, + aliases: { ...DRY_RUN_ALIASES, a: "attach" }, + }, + async *func( + this: SentryContext, + flags: CommentFlags, + target: IssueTarget, + text: string, + ) { + const paths = flags.attach ?? []; + // Read and check every file before anything is uploaded. + const videos = await Promise.all(paths.map(readLocalVideo)); + const { org, issue } = await target.resolved; + + if (flags["dry-run"]) { + yield new CommandOutput({ + text, + attachments: videos.map((video) => ({ + id: "", + name: video.name, + url: "", + })), + dryRun: true, + }); + return { hint: `Issue: ${issue.shortId}. Nothing was uploaded.` }; + } + + const { comment } = await withProgress( + { + message: videos.length + ? `Uploading ${videos.length} video(s) and posting comment...` + : "Posting comment...", + json: flags.json, + }, + () => createIssueCommentWithVideos(org, issue.id, text, videos), + ); + yield new CommandOutput( + toOutput(comment, await resolveOrgRegion(org), org, issue.id), + ); + return { hint: `Issue: ${issue.shortId}.` }; + }, +}); + +type CommentsFlags = { + readonly json: boolean; + readonly fields?: string[]; + readonly download?: string; +}; + +export const commentsCommand = buildCommand({ + docs: { + brief: "List an issue's comments and their videos", + fullDescription: + "Show an issue's comments, newest first, with any videos attached to them.\n\n" + + "Use --download to save every attached video into a directory. Files are\n" + + "named - so videos with the same name do not\n" + + "overwrite each other.", + examples: [ + { + description: "Read the comments on an issue", + run: "issue comments my-org/FRONT-ABC", + }, + { + description: "Save the attached videos to ./videos", + run: "issue comments FRONT-ABC --download ./videos", + }, + { + description: "Get comments and video URLs as JSON", + run: "issue comments FRONT-ABC --json --fields author,text,attachments", + }, + ], + }, + output: { + human: formatIssueComments, + schema: IssueCommentOutputSchema, + }, + parameters: { + positional: issuePositional({ command: "comments" }), + flags: { + download: { + kind: "parsed", + parse: parseDirectoryPath, + brief: "Directory to save attached videos into", + optional: true, + }, + }, + aliases: { d: "download" }, + }, + async *func(this: SentryContext, flags: CommentsFlags, target: IssueTarget) { + const { org, issue } = await target.resolved; + const [comments, regionUrl] = await withProgress( + { message: "Fetching comments...", json: flags.json }, + () => + Promise.all([listIssueComments(org, issue.id), resolveOrgRegion(org)]), + ); + const output = comments.map((comment) => + toOutput(comment, regionUrl, org, issue.id), + ); + + if (flags.download !== undefined) { + const dir = flags.download; + await mkdir(dir, { recursive: true }); + for (const comment of output) { + for (const attachment of comment.attachments) { + const destPath = join( + dir, + `${attachment.id}-${basename(attachment.name)}`, + ); + await withProgress( + { message: `Downloading ${attachment.name}...`, json: flags.json }, + () => + downloadIssueCommentAttachment( + org, + issue.id, + attachment.id, + destPath, + ), + ); + attachment.savedTo = destPath; + } + } + } + + yield new CommandOutput(output); + return { hint: `Issue: ${issue.shortId}. ${output.length} comment(s).` }; + }, +}); diff --git a/packages/cli/src/commands/issue/index.ts b/packages/cli/src/commands/issue/index.ts index 3473a3d8c9..c4b928c515 100644 --- a/packages/cli/src/commands/issue/index.ts +++ b/packages/cli/src/commands/issue/index.ts @@ -1,6 +1,7 @@ import { buildRouteMap } from "../../lib/route-map.js"; import { topLevelBrief } from "../../top-level-briefs.js"; import { archiveCommand } from "./archive.js"; +import { commentCommand, commentsCommand } from "./comments.js"; import { eventsCommand } from "./events.js"; import { explainCommand } from "./explain.js"; import { linkCommand } from "./link.js"; @@ -18,6 +19,8 @@ export const issueRoute = buildRouteMap({ list: listCommand, events: eventsCommand, tags: tagsCommand, + comment: commentCommand, + comments: commentsCommand, explain: explainCommand, plan: planCommand, view: viewCommand, @@ -39,6 +42,8 @@ export const issueRoute = buildRouteMap({ " list List issues in a project\n" + " events List events for a specific issue\n" + " tags Show the top values of an issue tag\n" + + " comment Comment on an issue, optionally attaching videos\n" + + " comments List an issue's comments and their videos\n" + " view View details of one or more issues\n" + " explain Analyze one or more issues using Seer AI\n" + " plan Generate a solution plan using Seer AI\n" + diff --git a/packages/cli/src/lib/api-client.ts b/packages/cli/src/lib/api-client.ts index efc7213664..7db16f7a5a 100644 --- a/packages/cli/src/lib/api-client.ts +++ b/packages/cli/src/lib/api-client.ts @@ -105,6 +105,14 @@ export { rawApiRequest, } from "./api/infrastructure.js"; export { getIssueTag } from "./api/issue-tags.js"; +export { + createIssueCommentWithVideos, + downloadIssueCommentAttachment, + type IssueComment, + listIssueComments, + type LocalVideo, + readLocalVideo, +} from "./api/issue-comments.js"; export { buildIssueListCollapse, findIssueInOrgs, diff --git a/packages/cli/src/lib/api/issue-comments.ts b/packages/cli/src/lib/api/issue-comments.ts new file mode 100644 index 0000000000..5de9c3bcf3 --- /dev/null +++ b/packages/cli/src/lib/api/issue-comments.ts @@ -0,0 +1,222 @@ +/** + * Issue comments and the videos attached to them. + * + * Comments, and the `comment-attachments/` upload and download routes, are + * not in the public API schema, so these calls build their requests by hand. + */ + +import { createWriteStream } from "node:fs"; +import { readFile, stat } from "node:fs/promises"; +import { basename } from "node:path"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import type { ReadableStream as NodeReadableStream } from "node:stream/web"; +import { + appendCommentAttachments, + COMMENT_ATTACHMENT_EXTENSIONS, + type CommentAttachment, + commentAttachmentContentType, + commentAttachmentPath, +} from "@sentry/mcp-core/comment-attachments"; +import { + array, + type InferOutput, + looseObject, + nullish, + number, + object, + parse, + string, +} from "valibot"; +import { isNetworkError, ValidationError } from "../errors.js"; +import { resolveOrgRegion } from "../region.js"; +import { getSdkConfig } from "../sentry-client.js"; +import { + API_MAX_PER_PAGE, + apiRequestToRegion, + autoPaginate, + paginatedResponse, + parseLinkHeader, + throwApiError, + throwRawApiError, +} from "./infrastructure.js"; + +/** An issue comment, as the comments endpoint returns it. */ +export const IssueCommentSchema = looseObject({ + id: string(), + dateCreated: string(), + data: looseObject({ text: nullish(string()) }), + user: nullish( + looseObject({ + name: nullish(string()), + email: nullish(string()), + }), + ), + sentry_app: nullish(looseObject({ name: nullish(string()) })), +}); + +export type IssueComment = InferOutput; + +const CommentAttachmentSchema = object({ + id: string(), + name: string(), + size: number(), + contentType: string(), + url: string(), +}); + +/** One page of an issue's comments, newest first. */ +async function fetchIssueCommentPage( + regionUrl: string, + orgSlug: string, + issueId: string, + cursor: string | undefined, +) { + const { data, headers } = await apiRequestToRegion( + regionUrl, + `/organizations/${encodeURIComponent(orgSlug)}/issues/${encodeURIComponent(issueId)}/comments/`, + { + params: { per_page: API_MAX_PER_PAGE, cursor }, + schema: array(IssueCommentSchema), + }, + ); + const { nextCursor } = parseLinkHeader(headers.get("link") ?? null); + return paginatedResponse(data, nextCursor); +} + +/** Every comment on an issue, newest first, following pagination. */ +export async function listIssueComments( + orgSlug: string, + issueId: string, +): Promise { + const regionUrl = await resolveOrgRegion(orgSlug); + const { data } = await autoPaginate( + (cursor) => fetchIssueCommentPage(regionUrl, orgSlug, issueId, cursor), + Number.MAX_SAFE_INTEGER, + ); + return data; +} + +/** Post a comment on an issue. */ +export async function createIssueComment( + orgSlug: string, + issueId: string, + text: string, +): Promise { + const { data } = await apiRequestToRegion( + await resolveOrgRegion(orgSlug), + `/organizations/${encodeURIComponent(orgSlug)}/issues/${encodeURIComponent(issueId)}/comments/`, + { method: "POST", body: { text }, schema: IssueCommentSchema }, + ); + return data; +} + +/** A local video checked and ready to upload. */ +export type LocalVideo = { + name: string; + contentType: string; + data: Uint8Array; +}; + +/** + * Read a video to attach. Both the extension and the file's leading bytes must + * be a supported video, so nothing else is uploaded by mistake. + */ +export async function readLocalVideo(path: string): Promise { + const info = await stat(path).catch(() => null); + if (!info?.isFile()) { + throw new ValidationError(`${path} is not a file.`, "attach"); + } + const data = new Uint8Array(await readFile(path)); + const name = basename(path); + const contentType = commentAttachmentContentType(name, data); + if (!contentType) { + throw new ValidationError( + `${name} is not a supported video. Attach ${COMMENT_ATTACHMENT_EXTENSIONS.join(", ")} files.`, + "attach", + ); + } + return { name, contentType, data }; +} + +/** Upload a video for an issue comment; the comment then links its `url`. */ +export async function uploadIssueCommentAttachment( + orgSlug: string, + issueId: string, + video: LocalVideo, +): Promise { + const regionUrl = await resolveOrgRegion(orgSlug); + const url = `${regionUrl.replace(/\/$/, "")}/api/0/organizations/${encodeURIComponent(orgSlug)}/issues/${encodeURIComponent(issueId)}/comment-attachments/`; + const form = new FormData(); + form.append( + "file", + new Blob([new Uint8Array(video.data)], { type: video.contentType }), + video.name, + ); + + let response: Response; + try { + response = await getSdkConfig(regionUrl).fetch(url, { + method: "POST", + body: form, + }); + } catch (error) { + if (isNetworkError(error)) { + throwApiError(error, undefined, "Video upload failed"); + } + throw error; + } + if (!response.ok) { + await throwRawApiError(response, url, "Video upload failed"); + } + return parse(CommentAttachmentSchema, await response.json()); +} + +/** Post a comment with videos uploaded first and linked after the text. */ +export async function createIssueCommentWithVideos( + orgSlug: string, + issueId: string, + text: string, + videos: readonly LocalVideo[], +): Promise<{ comment: IssueComment; attachments: CommentAttachment[] }> { + const attachments: CommentAttachment[] = []; + for (const video of videos) { + attachments.push( + await uploadIssueCommentAttachment(orgSlug, issueId, video), + ); + } + const comment = await createIssueComment( + orgSlug, + issueId, + appendCommentAttachments(text, attachments), + ); + return { comment, attachments }; +} + +/** + * Download one attached video to `destPath`, streaming so large recordings + * never sit in memory. + * + * The URL is rebuilt from the issue and the numeric attachment ID instead of + * the link in the comment, which anyone in the organization can write. + */ +export async function downloadIssueCommentAttachment( + orgSlug: string, + issueId: string, + attachmentId: string, + destPath: string, +): Promise { + if (!/^\d+$/.test(attachmentId)) { + throw new ValidationError(`Invalid attachment ID: ${attachmentId}`); + } + const regionUrl = await resolveOrgRegion(orgSlug); + const url = `${regionUrl.replace(/\/$/, "")}${commentAttachmentPath(orgSlug, issueId, attachmentId)}`; + const response = await getSdkConfig(regionUrl).fetch(url, { + method: "GET", + }); + if (!(response.ok && response.body)) { + await throwRawApiError(response, url, "Video download failed"); + } + const body = response.body as NodeReadableStream>; + await pipeline(Readable.fromWeb(body), createWriteStream(destPath)); +} diff --git a/packages/cli/src/lib/command-suggestions.ts b/packages/cli/src/lib/command-suggestions.ts index ae67a0cc2d..66a06b2e8f 100644 --- a/packages/cli/src/lib/command-suggestions.ts +++ b/packages/cli/src/lib/command-suggestions.ts @@ -63,14 +63,6 @@ const SUGGESTIONS: ReadonlyMap< explanation: "Issue assignment is available via the API", }, ], - [ - "issue/comment", - { - command: () => - sentry`api /api/0/organizations/{org}/issues/{issue_id}/comments/ --method POST --data '{"text":"..."}'`, - explanation: "Issue commenting is available via the API", - }, - ], // --- old sentry-cli commands (~5 events) --- ["cli/info", { command: () => sentry`auth status` }], diff --git a/packages/cli/src/lib/formatters/issue-comments.ts b/packages/cli/src/lib/formatters/issue-comments.ts new file mode 100644 index 0000000000..78bb8468fb --- /dev/null +++ b/packages/cli/src/lib/formatters/issue-comments.ts @@ -0,0 +1,33 @@ +/** + * Human output for issue comments and their attached videos. + */ + +import type { IssueCommentOutput } from "../../output-schemas/issue.js"; +import { sanitize } from "./local.js"; +import { muted } from "./index.js"; + +function formatAttachments(comment: IssueCommentOutput): string[] { + return comment.attachments.map((attachment) => { + const where = attachment.savedTo + ? `saved to ${sanitize(attachment.savedTo)}` + : sanitize(attachment.url); + return ` ${muted("video")} ${sanitize(attachment.name)} ${muted(where)}`; + }); +} + +/** One comment: who and when, its text, then its videos. */ +export function formatIssueComment(comment: IssueCommentOutput): string { + const heading = comment.dryRun + ? muted("Would post (dry run)") + : `${sanitize(comment.author ?? "Unknown")} ${muted(comment.dateCreated ?? "")}`; + const lines = comment.text.split("\n").map((line) => ` ${sanitize(line)}`); + return [heading, ...lines, ...formatAttachments(comment)].join("\n") + "\n"; +} + +/** Comments newest first, separated by a blank line. */ +export function formatIssueComments(comments: IssueCommentOutput[]): string { + if (comments.length === 0) { + return "No comments on this issue.\n"; + } + return comments.map(formatIssueComment).join("\n"); +} diff --git a/packages/cli/src/lib/mcp/local-files.ts b/packages/cli/src/lib/mcp/local-files.ts new file mode 100644 index 0000000000..8c1965ef00 --- /dev/null +++ b/packages/cli/src/lib/mcp/local-files.ts @@ -0,0 +1,48 @@ +/** + * Local file access for MCP tools that upload files, such as videos attached + * to issue comments. Only the stdio server runs on the user's machine, so only + * it hands this reader to mcp-core. + * + * The paths come from the model, which may be following injected + * instructions, so reads are confined to the directory the server was started + * in. Symlinks are resolved before that check, so a link inside the directory + * cannot reach a file outside it. + */ + +import { readFile, realpath, stat } from "node:fs/promises"; +import { basename, isAbsolute, relative, resolve } from "node:path"; +import type { LocalFile } from "@sentry/mcp-core/types"; + +/** True when `path` is `root` or inside it. */ +function isWithin(root: string, path: string): boolean { + const fromRoot = relative(root, path); + return ( + fromRoot === "" || !(fromRoot.startsWith("..") || isAbsolute(fromRoot)) + ); +} + +/** + * Read one regular file named in a tool call, from `root` or below it. + * + * @param root Directory files may be read from (the server's working directory) + */ +export async function readLocalFile( + path: string, + root: string = process.cwd(), +): Promise { + const realRoot = await realpath(root); + const realPath = await realpath(resolve(realRoot, path)); + if (!isWithin(realRoot, realPath)) { + throw new Error( + `only files in ${realRoot} can be attached; move the file there or start the MCP server from its directory`, + ); + } + const info = await stat(realPath); + if (!info.isFile()) { + throw new Error("not a regular file"); + } + return { + name: basename(realPath), + data: new Uint8Array(await readFile(realPath)), + }; +} diff --git a/packages/cli/src/lib/mcp/server.ts b/packages/cli/src/lib/mcp/server.ts index 1ceee0392c..dff4d1ae44 100644 --- a/packages/cli/src/lib/mcp/server.ts +++ b/packages/cli/src/lib/mcp/server.ts @@ -44,6 +44,7 @@ import { } from "../telemetry/offline-transport.js"; import { makeNodeTransportWithDeadline } from "../telemetry/zstd-transport.js"; import type { McpServerConfig } from "./config.js"; +import { readLocalFile } from "./local-files.js"; import { reportCliError } from "../error-reporting.js"; import { omitUndefined } from "../omit-undefined.js"; @@ -441,6 +442,8 @@ export async function serveMcpStdio( }), experimentalMode: config.experimental, transport: "stdio", + // Runs on the user's machine, so tools can attach the user's files. + readLocalFile: (path) => readLocalFile(path), // mcp-core uses the returned token for later tool calls, so a // long-running server recovers from an expired CLI session. ...(options.refreshAccessToken && { diff --git a/packages/cli/src/output-schemas/issue.ts b/packages/cli/src/output-schemas/issue.ts index 9bc401d23a..92956f0e24 100644 --- a/packages/cli/src/output-schemas/issue.ts +++ b/packages/cli/src/output-schemas/issue.ts @@ -20,9 +20,10 @@ import { pipe, string, unknown, + type InferOutput, } from "valibot"; import type { SentryEvent } from "../types/index.js"; -import { opaque } from "./output.js"; +import { DryRunOutputField, opaque } from "./output.js"; /** * Valibot schema describing the key fields of a {@link SentryIssue} for JSON output. @@ -143,3 +144,38 @@ export const IssueTagsOutputSchema = object({ ), ), }); + +/** A video attached to an issue comment. */ +const IssueCommentAttachmentOutput = object({ + id: pipe(string(), description("Attachment ID")), + name: pipe(string(), description("Video file name")), + url: pipe(string(), description("API URL that streams the video")), + savedTo: optional( + pipe( + string(), + description("Local path the video was saved to (--download)"), + ), + ), +}); + +/** JSON output of `issue comment` and each item of `issue comments`. */ +export const IssueCommentOutputSchema = object({ + id: optional( + pipe(string(), description("Comment ID; absent with --dry-run")), + ), + dateCreated: optional( + pipe(string(), description("When the comment was posted")), + ), + author: optional(pipe(string(), description("Who posted the comment"))), + text: pipe( + string(), + description("Comment text, including links to attached videos"), + ), + attachments: pipe( + array(IssueCommentAttachmentOutput), + description("Videos attached to the comment"), + ), + dryRun: DryRunOutputField, +}); + +export type IssueCommentOutput = InferOutput; diff --git a/packages/cli/test/commands/issue/comments.test.ts b/packages/cli/test/commands/issue/comments.test.ts new file mode 100644 index 0000000000..4f00cde131 --- /dev/null +++ b/packages/cli/test/commands/issue/comments.test.ts @@ -0,0 +1,472 @@ +/** + * Issue comment command integration tests. + * + * Exercise routing, issue resolution, the HTTP client, video checks, and + * output together. Only the external HTTP boundary is mocked. + */ + +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { run } from "@stricli/core"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { app } from "../../../src/app.js"; +import type { SentryContext } from "../../../src/context.js"; +import { setAuthToken } from "../../../src/lib/db/auth.js"; +import { setOrgRegion } from "../../../src/lib/db/regions.js"; +import { mockFetch, useEnvSandbox, useTestConfigDir } from "../../helpers.js"; + +const getConfigDir = useTestConfigDir("issue-comments-", { + isolateProjectRoot: true, +}); +useEnvSandbox(["SENTRY_AUTH_TOKEN", "SENTRY_TOKEN", "SENTRY_PLAIN_OUTPUT"]); + +const REGION_URL = "https://de.sentry.io"; +const ISSUE_PATH = "/api/0/organizations/test-org/issues/12345/"; +const ISSUE = { + id: "12345", + shortId: "FRONT-ABC", + title: "Example application error", + count: "1000", + userCount: 20, + status: "unresolved", + project: { id: "42", slug: "frontend", name: "Frontend" }, + permalink: "https://test-org.sentry.io/issues/12345/", +}; +const MP4 = Uint8Array.from([0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69]); +const VIDEO_PATH = `${ISSUE_PATH}comment-attachments/7/`; +const VIDEO_BYTES = "video-bytes"; + +let originalFetch: typeof globalThis.fetch; +let requests: Request[]; +let uploads: Array<{ name: string; type: string; size: number }>; +let postedText: string | undefined; +let uploadStatus: number; +let commentsBody: unknown[] | undefined; +let commentPages: unknown[][] | undefined; + +beforeEach(() => { + originalFetch = globalThis.fetch; + requests = []; + uploads = []; + postedText = undefined; + uploadStatus = 201; + commentsBody = undefined; + commentPages = undefined; + setAuthToken("test-token"); + setOrgRegion("test-org", REGION_URL); + globalThis.fetch = mockFetch(async (input, init) => { + const request = new Request(input, init); + requests.push(request); + const { pathname } = new URL(request.url); + if (pathname === ISSUE_PATH) { + return Response.json(ISSUE); + } + if (pathname === `${ISSUE_PATH}comment-attachments/`) { + if (uploadStatus !== 201) { + return Response.json( + { detail: "File is too large. The maximum size is 100 MB." }, + { status: uploadStatus }, + ); + } + const file = (await request.formData()).get("file"); + if (!(file instanceof File)) { + throw new Error("upload without a file"); + } + uploads.push({ name: file.name, type: file.type, size: file.size }); + return Response.json( + { + id: String(uploads.length), + name: file.name, + size: file.size, + contentType: file.type, + url: `${ISSUE_PATH}comment-attachments/${uploads.length}/`, + }, + { status: 201 }, + ); + } + if (pathname === `${ISSUE_PATH}comments/` && request.method === "POST") { + postedText = ((await request.json()) as { text: string }).text; + return Response.json({ + id: "900", + dateCreated: "2026-10-21T12:00:00Z", + user: { name: "Jane Developer" }, + data: { text: postedText }, + }); + } + if (pathname === `${ISSUE_PATH}comments/` && commentsBody) { + return Response.json(commentsBody); + } + if (pathname === `${ISSUE_PATH}comments/` && commentPages) { + const cursor = new URL(request.url).searchParams.get("cursor") ?? ""; + const index = cursor ? Number(cursor.split(":")[1]) : 0; + const hasNext = index + 1 < commentPages.length; + return Response.json(commentPages[index], { + headers: { + Link: `<${REGION_URL}${ISSUE_PATH}comments/>; rel="next"; results="${hasNext}"; cursor="0:${index + 1}:0"`, + }, + }); + } + if (pathname === `${ISSUE_PATH}comments/`) { + return Response.json([ + { + id: "901", + dateCreated: "2026-10-21T12:00:00Z", + user: { name: "Jane Developer" }, + data: { + text: `Crash on save\n[repro.mp4](${VIDEO_PATH})\n[docs](https://docs.sentry.io/)`, + }, + }, + { + id: "900", + dateCreated: "2026-10-20T12:00:00Z", + user: null, + sentry_app: { name: "Linear" }, + data: { text: "Linked to an external ticket" }, + }, + ]); + } + if (pathname === VIDEO_PATH) { + return new Response(VIDEO_BYTES, { + headers: { "Content-Type": "video/mp4" }, + }); + } + throw new Error(`Unexpected request: ${request.method} ${request.url}`); + }); +}); + +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +async function runCli(args: string[]) { + const stdout: string[] = []; + const stderr: string[] = []; + const writer = (sink: string[]) => ({ + write(value: string | Uint8Array) { + sink.push(String(value)); + return true; + }, + }); + const context: SentryContext = { + process: { + ...process, + stdout: writer(stdout), + stderr: writer(stderr), + exitCode: undefined, + } as unknown as typeof process, + env: process.env, + cwd: getConfigDir(), + homeDir: getConfigDir(), + configDir: getConfigDir(), + stdin: process.stdin, + stdout: writer(stdout), + stderr: writer(stderr), + }; + await run(app, args, context); + return { + stdout: stdout.join(""), + stderr: stderr.join(""), + exitCode: context.process.exitCode ?? 0, + }; +} + +function writeFile(name: string, data: Uint8Array | string): string { + const path = join(getConfigDir(), name); + writeFileSync(path, data); + return path; +} + +function postRequests() { + return requests.filter((request) => request.method === "POST"); +} + +describe("issue comment", () => { + test("posts a comment", async () => { + const result = await runCli([ + "issue", + "comment", + "test-org/12345", + "Fixed in the next deploy", + "--json", + ]); + + expect(result.exitCode).toBe(0); + expect(postedText).toBe("Fixed in the next deploy"); + expect(JSON.parse(result.stdout)).toEqual({ + id: "900", + dateCreated: "2026-10-21T12:00:00Z", + author: "Jane Developer", + text: "Fixed in the next deploy", + attachments: [], + }); + }); + + test("uploads videos and links them after the text", async () => { + const first = writeFile("repro.mp4", MP4); + const second = writeFile("take2.mov", MP4); + + const result = await runCli([ + "issue", + "comment", + "test-org/12345", + "Repro below", + "--attach", + first, + "--attach", + second, + "--json", + ]); + + expect(result.exitCode).toBe(0); + expect(uploads).toEqual([ + { name: "repro.mp4", type: "video/mp4", size: MP4.length }, + { name: "take2.mov", type: "video/quicktime", size: MP4.length }, + ]); + expect(postedText).toBe( + `Repro below\n[repro.mp4](${ISSUE_PATH}comment-attachments/1/)\n[take2.mov](${ISSUE_PATH}comment-attachments/2/)`, + ); + expect(JSON.parse(result.stdout).attachments).toEqual([ + { + id: "1", + name: "repro.mp4", + url: `${REGION_URL}${ISSUE_PATH}comment-attachments/1/`, + }, + { + id: "2", + name: "take2.mov", + url: `${REGION_URL}${ISSUE_PATH}comment-attachments/2/`, + }, + ]); + const upload = postRequests()[0]; + expect(upload?.headers.get("Authorization")).toBe("Bearer test-token"); + expect(upload?.headers.get("Content-Type")).toMatch( + /^multipart\/form-data; boundary=/, + ); + }); + + test("refuses a file that is not a video before uploading anything", async () => { + const video = writeFile("repro.mp4", MP4); + const key = writeFile("id_rsa.mp4", "-----BEGIN OPENSSH PRIVATE KEY-----"); + + const result = await runCli([ + "issue", + "comment", + "test-org/12345", + "Repro", + "--attach", + video, + "--attach", + key, + ]); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain("id_rsa.mp4 is not a supported video"); + expect(postRequests()).toEqual([]); + }); + + test("refuses a missing file", async () => { + const result = await runCli([ + "issue", + "comment", + "test-org/12345", + "Repro", + "--attach", + join(getConfigDir(), "missing.mp4"), + ]); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain("is not a file"); + expect(postRequests()).toEqual([]); + }); + + test("shows the server's size limit and posts nothing", async () => { + uploadStatus = 413; + const video = writeFile("big.mp4", MP4); + + const result = await runCli([ + "issue", + "comment", + "test-org/12345", + "Repro", + "--attach", + video, + ]); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toContain("File is too large"); + expect(postedText).toBeUndefined(); + }); + + test("--dry-run checks the files without uploading or posting", async () => { + const video = writeFile( + "repro.webm", + Uint8Array.from([0x1a, 0x45, 0xdf, 0xa3]), + ); + + const result = await runCli([ + "issue", + "comment", + "test-org/12345", + "Repro", + "--attach", + video, + "--dry-run", + "--json", + ]); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + text: "Repro", + dryRun: true, + attachments: [{ name: "repro.webm" }], + }); + expect(postRequests()).toEqual([]); + }); +}); + +describe("issue comments", () => { + test("follows pagination to list every comment", async () => { + const comment = (id: string) => ({ + id, + dateCreated: "2026-10-21T12:00:00Z", + user: { name: "Jane Developer" }, + data: { text: `comment ${id}` }, + }); + commentPages = [[comment("3"), comment("2")], [comment("1")]]; + + const result = await runCli([ + "issue", + "comments", + "test-org/12345", + "--json", + ]); + + expect(result.exitCode).toBe(0); + expect( + JSON.parse(result.stdout).map((item: { id: string }) => item.id), + ).toEqual(["3", "2", "1"]); + const listRequests = requests.filter( + (request) => new URL(request.url).pathname === `${ISSUE_PATH}comments/`, + ); + expect(listRequests).toHaveLength(2); + expect(new URL(listRequests[1]?.url ?? "").searchParams.get("cursor")).toBe( + "0:1:0", + ); + }); + + test("lists video URLs for the issue being read, not the link's", async () => { + commentsBody = [ + { + id: "902", + dateCreated: "2026-10-21T12:00:00Z", + user: { name: "Mallory" }, + data: { + text: "[a.mp4](/api/0/organizations/other-org/issues/999/comment-attachments/7/)", + }, + }, + ]; + + const result = await runCli([ + "issue", + "comments", + "test-org/12345", + "--json", + ]); + + expect(JSON.parse(result.stdout)[0].attachments).toEqual([ + { id: "7", name: "a.mp4", url: `${REGION_URL}${VIDEO_PATH}` }, + ]); + }); + + test("--download builds the URL from the issue, not the comment link", async () => { + const dir = join(getConfigDir(), "videos"); + commentsBody = [ + { + id: "902", + dateCreated: "2026-10-21T12:00:00Z", + user: { name: "Mallory" }, + data: { + text: "[a.mp4](/api/0/organizations/other-org/issues/999/comment-attachments/7/)\n[b.mp4](/api/0/organizations/../issues/1/comment-attachments/8/)", + }, + }, + ]; + + const result = await runCli([ + "issue", + "comments", + "test-org/12345", + "--download", + dir, + "--json", + ]); + + expect(result.exitCode).toBe(0); + const downloads = requests + .filter((request) => request.url.includes("comment-attachments")) + .map((request) => new URL(request.url).pathname); + expect(downloads).toEqual([VIDEO_PATH]); + expect(JSON.parse(result.stdout)[0].attachments).toHaveLength(1); + }); + + test("lists comments with their videos", async () => { + const result = await runCli([ + "issue", + "comments", + "test-org/12345", + "--json", + ]); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([ + { + id: "901", + dateCreated: "2026-10-21T12:00:00Z", + author: "Jane Developer", + text: `Crash on save\n[repro.mp4](${VIDEO_PATH})\n[docs](https://docs.sentry.io/)`, + attachments: [ + { id: "7", name: "repro.mp4", url: `${REGION_URL}${VIDEO_PATH}` }, + ], + }, + { + id: "900", + dateCreated: "2026-10-20T12:00:00Z", + author: "Linear", + text: "Linked to an external ticket", + attachments: [], + }, + ]); + }); + + test("renders comments for people", async () => { + const result = await runCli(["issue", "comments", "test-org/12345"]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("Jane Developer"); + expect(result.stdout).toContain("repro.mp4"); + expect(result.stdout).toContain(`${REGION_URL}${VIDEO_PATH}`); + }); + + test("--download saves each video into the directory", async () => { + const dir = join(getConfigDir(), "videos"); + mkdirSync(dir); + + const result = await runCli([ + "issue", + "comments", + "test-org/12345", + "--download", + dir, + "--json", + ]); + + expect(result.exitCode).toBe(0); + const savedTo = join(dir, "7-repro.mp4"); + expect(existsSync(savedTo)).toBe(true); + expect(readFileSync(savedTo, "utf8")).toBe(VIDEO_BYTES); + expect(JSON.parse(result.stdout)[0].attachments[0].savedTo).toBe(savedTo); + const download = requests.find( + (request) => new URL(request.url).pathname === VIDEO_PATH, + ); + expect(download?.headers.get("Authorization")).toBe("Bearer test-token"); + }); +}); diff --git a/packages/cli/test/lib/command-suggestions.test.ts b/packages/cli/test/lib/command-suggestions.test.ts index 617514ba93..1d064f2688 100644 --- a/packages/cli/test/lib/command-suggestions.test.ts +++ b/packages/cli/test/lib/command-suggestions.test.ts @@ -10,6 +10,7 @@ import { homedir } from "node:os"; import { run } from "@stricli/core"; import { afterEach, describe, expect, test, vi } from "vitest"; import { app, routes } from "../../src/app.js"; +import { sentry } from "../../src/lib/app-identity.js"; import { getCommandSuggestion } from "../../src/lib/command-suggestions.js"; import { isRouteMap, type RouteMap } from "../../src/lib/introspect.js"; import { useTestConfigDir } from "../helpers.js"; @@ -53,11 +54,11 @@ describe("getCommandSuggestion", () => { // --- Pattern 3: mutation commands --- test("suggests native resolve for the unambiguous close synonym", () => { expect(getCommandSuggestion("issue", "close")).toEqual({ - command: "sentry issue resolve ", + command: sentry`issue resolve `, }); }); - test.each(["update", "set-status", "assign", "comment"])( + test.each(["update", "set-status", "assign"])( "keeps the API suggestion for issue %s without an exact native equivalent", (command) => { expect(getCommandSuggestion("issue", command)?.command).toMatch( @@ -90,7 +91,7 @@ describe("getCommandSuggestion", () => { test("suggests send-event for 'cli/send-event'", () => { expect(getCommandSuggestion("cli", "send-event")?.command).toContain( - "sentry event send", + sentry`event send`, ); }); @@ -171,7 +172,7 @@ describe("command error suggestions", () => { async (command, flag, value, error) => { const output = await runIssue([command, "TEST-1", flag, value]); expect(output).toContain(error); - expect(output).not.toContain("sentry api"); + expect(output).not.toContain(sentry`api`); }, ); }); diff --git a/packages/cli/test/lib/mcp/local-files.test.ts b/packages/cli/test/lib/mcp/local-files.test.ts new file mode 100644 index 0000000000..a6ea7ff721 --- /dev/null +++ b/packages/cli/test/lib/mcp/local-files.test.ts @@ -0,0 +1,67 @@ +import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative } from "node:path"; +import { describe, expect, test } from "vitest"; +import { readLocalFile } from "../../../src/lib/mcp/local-files.js"; + +function tempDir(): string { + return mkdtempSync(join(tmpdir(), "sentry-local-files-")); +} + +describe("readLocalFile", () => { + test("reads a file relative to the root", async () => { + const dir = tempDir(); + writeFileSync(join(dir, "repro.mp4"), Uint8Array.from([1, 2, 3])); + + const file = await readLocalFile("repro.mp4", dir); + + expect(file.name).toBe("repro.mp4"); + expect([...file.data]).toEqual([1, 2, 3]); + }); + + test("reads an absolute path inside the root", async () => { + const dir = tempDir(); + mkdirSync(join(dir, "videos")); + const path = join(dir, "videos", "clip.webm"); + writeFileSync(path, "x"); + + expect((await readLocalFile(path, dir)).name).toBe("clip.webm"); + }); + + test("refuses a file outside the root", async () => { + const root = tempDir(); + const outside = join(tempDir(), "private.mp4"); + writeFileSync(outside, "x"); + + await expect(readLocalFile(outside, root)).rejects.toThrow("only files in"); + await expect(readLocalFile(relative(root, outside), root)).rejects.toThrow( + "only files in", + ); + }); + + test("refuses a symlink inside the root that points outside it", async () => { + const root = tempDir(); + const outside = join(tempDir(), "private.mp4"); + writeFileSync(outside, "x"); + symlinkSync(outside, join(root, "innocent.mp4")); + + await expect(readLocalFile("innocent.mp4", root)).rejects.toThrow( + "only files in", + ); + }); + + test("refuses directories", async () => { + const dir = tempDir(); + mkdirSync(join(dir, "videos.mp4")); + + await expect(readLocalFile("videos.mp4", dir)).rejects.toThrow( + "not a regular file", + ); + }); + + test("fails for a missing file", async () => { + await expect(readLocalFile("missing.mp4", tempDir())).rejects.toThrow( + "ENOENT", + ); + }); +}); diff --git a/packages/mcp-core/package.json b/packages/mcp-core/package.json index ea61352bd0..d4e84738f3 100644 --- a/packages/mcp-core/package.json +++ b/packages/mcp-core/package.json @@ -29,6 +29,10 @@ "types": "./dist/api-client/index.d.ts", "default": "./dist/api-client/index.js" }, + "./comment-attachments": { + "types": "./dist/comment-attachments.d.ts", + "default": "./dist/comment-attachments.js" + }, "./constants": { "types": "./dist/constants.d.ts", "default": "./dist/constants.js" diff --git a/packages/mcp-core/src/api-client/client.ts b/packages/mcp-core/src/api-client/client.ts index 1b2d5f3dc3..c76896aca4 100644 --- a/packages/mcp-core/src/api-client/client.ts +++ b/packages/mcp-core/src/api-client/client.ts @@ -23,11 +23,13 @@ import { type ApiTarget, ApiValidationError, applyTimeParams, + buildSentryApiUrl, createApiClientCore, createApiError, createApiTransport, createIdempotentOperationMatcher, nextPageCursor, + readErrorResponse, readJsonResponse, type RetryPolicy, selectIdempotentWrites, @@ -149,6 +151,7 @@ import { IssueActivityListResponseSchema, IssueAlertRuleListSchema, IssueAlertRuleSchema, + IssueCommentAttachmentSchema, IssueCommentListSchema, IssueCommentSchema, IssueIntegrationListSchema, @@ -231,6 +234,7 @@ import type { IssueAlertRule, IssueAlertRuleList, IssueComment, + IssueCommentAttachment, IssueCommentList, IssueIntegrationList, IssueList, @@ -838,6 +842,14 @@ export class SentryApiService { * apiService.getIssueUrl("my-org", "PROJ-123") * ``` */ + /** + * Full URL for an API path that already carries the `/api/0` prefix, such + * as a comment attachment link read from comment text. + */ + getAbsoluteApiUrl(path: string): string { + return `${this.origin()}${path}`; + } + getIssueUrl(organizationSlug: string, issueId: string): string { return getIssueUrlUtil(this.host, organizationSlug, issueId, this.protocol); } @@ -4378,6 +4390,56 @@ export class SentryApiService { return IssueCommentSchema.parse(body); } + /** + * Uploads a video for an issue comment. The comment links the returned + * `url`; Sentry enforces the size limit and accepted video types. + */ + async uploadIssueCommentAttachment( + { + organizationSlug, + issueId, + fileName, + contentType, + data, + }: { + organizationSlug: string; + issueId: string; + fileName: string; + contentType: string; + data: Uint8Array; + }, + opts?: RequestOptions, + ): Promise { + const path = apiPath`/organizations/${organizationSlug}/issues/${issueId}/comment-attachments/`; + const form = new FormData(); + form.append( + "file", + new Blob([new Uint8Array(data)], { type: contentType }), + fileName, + ); + // The core sends every body as JSON, so a multipart upload goes straight + // to the transport and lets fetch set the multipart boundary. + const response = await transport.request( + buildSentryApiUrl(this.origin(opts?.host), path), + { + method: "POST", + headers: this.requestHeaders(), + body: form, + ...(this.signal ? { signal: this.signal } : {}), + }, + ); + if (!response.ok) { + const body = await readErrorResponse(response); + throw createApiError( + body.detail ?? `Video upload failed (${response.status})`, + response.status, + body.detail, + body.json, + ); + } + return IssueCommentAttachmentSchema.parse(await readJsonResponse(response)); + } + async getIssueActivity( { organizationSlug, diff --git a/packages/mcp-core/src/api-client/schema.ts b/packages/mcp-core/src/api-client/schema.ts index 79b4a826f5..45b904838c 100644 --- a/packages/mcp-core/src/api-client/schema.ts +++ b/packages/mcp-core/src/api-client/schema.ts @@ -798,6 +798,15 @@ export const IssueCommentSchema = IssueActivitySchema.extend({ export const IssueCommentListSchema = z.array(IssueCommentSchema); +/** A video uploaded through an issue's `comment-attachments/` endpoint. */ +export const IssueCommentAttachmentSchema = z.object({ + id: z.string(), + name: z.string(), + size: z.number(), + contentType: z.string(), + url: z.string(), +}); + /** * Organization tag lists are backed by `TagKeySerializerResponse`, which only * guarantees `key` and `name`. Count fields are backend-dependent and may come diff --git a/packages/mcp-core/src/api-client/types.ts b/packages/mcp-core/src/api-client/types.ts index 505c8cd1f1..e9fd3027a8 100644 --- a/packages/mcp-core/src/api-client/types.ts +++ b/packages/mcp-core/src/api-client/types.ts @@ -86,6 +86,7 @@ import type { IssueAlertRuleListSchema, IssueAlertRuleSchema, IssueCommentListSchema, + IssueCommentAttachmentSchema, IssueCommentSchema, IssueIntegrationListSchema, IssueIntegrationSchema, @@ -218,6 +219,9 @@ export type Commit = z.infer; export type Issue = z.infer; export type IssueActivity = z.infer; export type IssueComment = z.infer; +export type IssueCommentAttachment = z.infer< + typeof IssueCommentAttachmentSchema +>; type IssueUpdateStatusDetails = NonNullable< NonNullable["statusDetails"] diff --git a/packages/mcp-core/src/comment-attachments.test.ts b/packages/mcp-core/src/comment-attachments.test.ts new file mode 100644 index 0000000000..3ea614a851 --- /dev/null +++ b/packages/mcp-core/src/comment-attachments.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "vitest"; +import { + appendCommentAttachments, + commentAttachmentContentType, + commentAttachmentMarkdown, + parseCommentAttachments, +} from "./comment-attachments"; + +const MP4 = new Uint8Array([0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69]); +const WEBM = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3, 0x01]); +const OGG = new Uint8Array([0x4f, 0x67, 0x67, 0x53, 0x00]); +const TEXT = new TextEncoder().encode("-----BEGIN OPENSSH PRIVATE KEY-----"); + +const PATH = "/api/0/organizations/my-org/issues/123/comment-attachments/5/"; + +describe("commentAttachmentContentType", () => { + it.each([ + ["clip.mp4", MP4, "video/mp4"], + ["clip.M4V", MP4, "video/mp4"], + ["clip.mov", MP4, "video/quicktime"], + ["clip.webm", WEBM, "video/webm"], + ["clip.ogv", OGG, "video/ogg"], + ])("accepts %s", (name, bytes, expected) => { + expect(commentAttachmentContentType(name, bytes)).toBe(expected); + }); + + it.each([ + ["a key renamed to a video", "id_rsa.mp4", TEXT], + ["a video with the wrong extension", "clip.webm", MP4], + ["an unsupported extension", "notes.txt", MP4], + ["a file without an extension", "clip", MP4], + ["an empty file", "clip.mp4", new Uint8Array()], + ])("rejects %s", (_label, name, bytes) => { + expect(commentAttachmentContentType(name, bytes)).toBeNull(); + }); +}); + +describe("parseCommentAttachments", () => { + it("reads attachment links and ignores other links", () => { + expect( + parseCommentAttachments( + `Repro below\n[repro.mp4](${PATH})\nSee [docs](https://docs.sentry.io/)`, + ), + ).toEqual([{ id: "5", name: "repro.mp4", path: PATH }]); + }); + + it("unescapes brackets in the file name", () => { + expect(parseCommentAttachments(`[take \\[2\\].mp4](${PATH})`)).toEqual([ + { id: "5", name: "take [2].mp4", path: PATH }, + ]); + }); + + it.each([ + "[x](/api/0/organizations/../issues/1/comment-attachments/5/)", + "[x](/api/0/organizations/my-org/issues/..%2F..%2Fusers/comment-attachments/5/)", + "[x](/api/0/organizations/my-org/issues/1/comment-attachments/5/../../)", + "[x](https://evil.example/api/0/organizations/o/issues/1/comment-attachments/5/)", + ])("ignores a link that is not a plain attachment path: %s", (text) => { + expect(parseCommentAttachments(text)).toEqual([]); + }); + + it("returns nothing for empty text", () => { + expect(parseCommentAttachments(null)).toEqual([]); + expect(parseCommentAttachments("")).toEqual([]); + }); +}); + +describe("appendCommentAttachments", () => { + it("adds one link per video after the text", () => { + expect( + appendCommentAttachments("Repro ", [ + { name: "a.mp4", url: PATH }, + { name: "b].mp4", url: PATH }, + ]), + ).toBe(`Repro\n[a.mp4](${PATH})\n[b\\].mp4](${PATH})`); + }); + + it("round-trips through parseCommentAttachments", () => { + const text = appendCommentAttachments("x", [ + { name: "we[ir]d\\.mp4", url: PATH }, + ]); + expect(parseCommentAttachments(text)[0]?.name).toBe("we[ir]d\\.mp4"); + }); + + it("escapes link text", () => { + expect(commentAttachmentMarkdown({ name: "[x]", url: PATH })).toBe( + `[\\[x\\]](${PATH})`, + ); + }); +}); diff --git a/packages/mcp-core/src/comment-attachments.ts b/packages/mcp-core/src/comment-attachments.ts new file mode 100644 index 0000000000..229f6552b8 --- /dev/null +++ b/packages/mcp-core/src/comment-attachments.ts @@ -0,0 +1,135 @@ +/** + * Videos attached to issue comments. + * + * Sentry stores each upload through the issue's `comment-attachments/` + * endpoint and the comment text links to it as Markdown. The CLI and the MCP + * server share these helpers so both accept the same files and read the same + * links back out of comment text. + */ + +/** Video types Sentry accepts for comment attachments, keyed by extension. */ +const VIDEO_TYPES_BY_EXTENSION: Readonly> = { + mp4: "video/mp4", + m4v: "video/mp4", + mov: "video/quicktime", + webm: "video/webm", + ogv: "video/ogg", + ogg: "video/ogg", +}; + +/** File extensions accepted for comment attachments, for help text. */ +export const COMMENT_ATTACHMENT_EXTENSIONS = Object.keys( + VIDEO_TYPES_BY_EXTENSION, +); + +function startsWith( + bytes: Uint8Array, + signature: readonly number[], + offset = 0, +) { + return signature.every((byte, index) => bytes[offset + index] === byte); +} + +/** True when the bytes begin like a container of the given video type. */ +function hasVideoSignature(contentType: string, bytes: Uint8Array): boolean { + switch (contentType) { + case "video/mp4": + case "video/quicktime": + // ISO base media: a box size, then the `ftyp` box type. + return startsWith(bytes, [0x66, 0x74, 0x79, 0x70], 4); + case "video/webm": + // EBML header. + return startsWith(bytes, [0x1a, 0x45, 0xdf, 0xa3]); + case "video/ogg": + return startsWith(bytes, [0x4f, 0x67, 0x67, 0x53]); // "OggS" + default: + return false; + } +} + +/** + * Content type to upload a file as, or null when it is not a supported video. + * + * Both the extension and the file's leading bytes must match, so a renamed + * text file, key or document is never sent as a video. + */ +export function commentAttachmentContentType( + fileName: string, + bytes: Uint8Array, +): string | null { + const extension = fileName.split(".").pop()?.toLowerCase() ?? ""; + const contentType = VIDEO_TYPES_BY_EXTENSION[extension]; + if (!contentType || !hasVideoSignature(contentType, bytes)) { + return null; + } + return contentType; +} + +/** A video uploaded to an issue, as the upload endpoint returns it. */ +export type CommentAttachment = { + id: string; + name: string; + size: number; + contentType: string; + /** API path, e.g. `/api/0/organizations/org/issues/1/comment-attachments/5/`. */ + url: string; +}; + +/** A video linked from comment text. */ +export type CommentAttachmentLink = { + id: string; + name: string; + /** API path of the video, as written in the comment. */ + path: string; +}; + +// Org and issue segments are slugs, numeric IDs or short IDs, so `.`/`..` +// segments and encoded characters never match: a link written by anyone in +// the org cannot point a download at another API route. +const ATTACHMENT_LINK = + /\[((?:\\.|[^\]\\])*)\]\((\/api\/0\/organizations\/[\w-]+\/issues\/[\w-]+\/comment-attachments\/(\d+)\/)\)/g; + +/** + * API path of a video attached to an issue's comments. Built from the issue + * being read rather than taken from the comment link, which anyone in the + * organization can write. + */ +export function commentAttachmentPath( + organizationSlug: string, + issueId: string, + attachmentId: string, +): string { + return `/api/0/organizations/${encodeURIComponent(organizationSlug)}/issues/${encodeURIComponent(issueId)}/comment-attachments/${encodeURIComponent(attachmentId)}/`; +} + +/** Markdown link for an uploaded video, with link-text brackets escaped. */ +export function commentAttachmentMarkdown(attachment: { + name: string; + url: string; +}): string { + const label = attachment.name.replace(/([\\[\]])/g, "\\$1"); + return `[${label}](${attachment.url})`; +} + +/** Videos linked from a comment's text, in the order they appear. */ +export function parseCommentAttachments( + text: string | null | undefined, +): CommentAttachmentLink[] { + if (!text) { + return []; + } + return Array.from(text.matchAll(ATTACHMENT_LINK), (match) => ({ + id: match[3] ?? "", + name: (match[1] ?? "").replace(/\\([\\[\]])/g, "$1"), + path: match[2] ?? "", + })); +} + +/** Comment text with each uploaded video's link appended on its own line. */ +export function appendCommentAttachments( + text: string, + attachments: ReadonlyArray<{ name: string; url: string }>, +): string { + const links = attachments.map(commentAttachmentMarkdown); + return [text.trimEnd(), ...links].filter((line) => line !== "").join("\n"); +} diff --git a/packages/mcp-core/src/skillDefinitions.json b/packages/mcp-core/src/skillDefinitions.json index cd770a91c3..9ac19a01f2 100644 --- a/packages/mcp-core/src/skillDefinitions.json +++ b/packages/mcp-core/src/skillDefinitions.json @@ -99,7 +99,7 @@ }, { "name": "get_issue_activity", - "description": "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when.", + "description": "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when, plus any videos attached to comments.", "requiredScopes": ["event:read"] }, { @@ -450,7 +450,7 @@ }, { "name": "get_issue_activity", - "description": "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when.", + "description": "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when, plus any videos attached to comments.", "requiredScopes": ["event:read"] }, { diff --git a/packages/mcp-core/src/toolDefinitions.json b/packages/mcp-core/src/toolDefinitions.json index 79b26b062e..8795078094 100644 --- a/packages/mcp-core/src/toolDefinitions.json +++ b/packages/mcp-core/src/toolDefinitions.json @@ -35,7 +35,16 @@ "type": "string", "minLength": 1, "maxLength": 4096, - "description": "The comment text, posted as is." + "description": "The comment text, posted as is. Links to attached videos are added after it." + }, + "attachmentPaths": { + "description": "Local paths of videos to attach (MP4, MOV, WebM or Ogg), such as a screen recording of the bug. Only works when the MCP server runs on the user's machine (`sentry mcp`), and only for files in the directory it was started in. Only attach files the user asked for.", + "maxItems": 5, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } } }, "required": ["text"] @@ -69,9 +78,36 @@ }, "text": { "type": ["string", "null"] + }, + "attachments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": ["id", "name", "url"], + "additionalProperties": false + }, + "description": "Videos uploaded with the note and linked from its text." } }, - "required": ["id", "type", "author", "dateCreated", "text"], + "required": [ + "id", + "type", + "author", + "dateCreated", + "text", + "attachments" + ], "additionalProperties": false } }, @@ -6521,7 +6557,7 @@ { "name": "get_issue_activity", "title": "Get Issue Activity", - "description": "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when.", + "description": "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when, plus any videos attached to comments.", "inputSchema": { "type": "object", "properties": { @@ -6602,6 +6638,27 @@ "text": { "type": ["string", "null"] }, + "attachments": { + "description": "Videos attached to a comment. Download one with `sentry issue comments --download `.", + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string", + "description": "API URL that streams the video." + } + }, + "required": ["id", "name", "url"], + "additionalProperties": false + } + }, "assignee": { "type": "object", "properties": { @@ -6855,6 +6912,27 @@ "text": { "type": ["string", "null"] }, + "attachments": { + "description": "Videos attached to a comment. Download one with `sentry issue comments --download `.", + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string", + "description": "API URL that streams the video." + } + }, + "required": ["id", "name", "url"], + "additionalProperties": false + } + }, "assignee": { "type": "object", "properties": { diff --git a/packages/mcp-core/src/tools/catalog/add-issue-note.test.ts b/packages/mcp-core/src/tools/catalog/add-issue-note.test.ts index b11e877d79..e666463f36 100644 --- a/packages/mcp-core/src/tools/catalog/add-issue-note.test.ts +++ b/packages/mcp-core/src/tools/catalog/add-issue-note.test.ts @@ -1,12 +1,28 @@ -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, assert, describe, expect, it } from "vitest"; import { mswServer } from "@sentry/mcp-server-mocks"; import { http, HttpResponse } from "msw"; import { assertStructuredOnlyResult, getStructuredContent, } from "../../test-utils/structured-content.js"; +import { UserInputError } from "../../errors.js"; +import type { LocalFile } from "../../types.js"; import addIssueNote, { addIssueNoteOutputSchema } from "./add-issue-note.js"; +const MP4 = new Uint8Array([0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69]); +const ATTACHMENTS_PATH = + "*/api/0/organizations/:org/issues/:issueId/comment-attachments/"; + +function localFiles(files: Record) { + return async (path: string) => { + const file = files[path]; + if (!file) { + throw new UserInputError(`No such file: ${path}`); + } + return file; + }; +} + const context = { constraints: { organizationSlug: null, @@ -57,6 +73,7 @@ describe("add_issue_note", () => { "issueId": "CLOUDFLARE-MCP-41", "issueUrl": "https://sentry-mcp-evals.sentry.io/issues/CLOUDFLARE-MCP-41", "note": { + "attachments": [], "author": "Jane Developer (Claude via MCP)", "dateCreated": "2025-04-14T12:34:56.000Z", "id": "comment-1", @@ -89,6 +106,7 @@ describe("add_issue_note", () => { "issueId": "CLOUDFLARE-MCP-41", "issueUrl": "https://sentry-mcp-evals.sentry.io/issues/CLOUDFLARE-MCP-41", "note": { + "attachments": [], "author": "Test User", "dateCreated": "2025-04-14T12:34:56.000Z", "id": "12345", @@ -99,4 +117,172 @@ describe("add_issue_note", () => { } `); }); + + it("uploads local videos and links them in the note", async () => { + const uploads: Array<{ name: string; type: string; size: number }> = []; + let postedText: unknown; + mswServer.use( + http.post(ATTACHMENTS_PATH, async ({ request, params }) => { + const file = (await request.formData()).get("file"); + assert(file instanceof File); + uploads.push({ name: file.name, type: file.type, size: file.size }); + return HttpResponse.json( + { + id: String(uploads.length), + name: file.name, + size: file.size, + contentType: file.type, + url: `/api/0/organizations/${String(params["org"])}/issues/${String(params["issueId"])}/comment-attachments/${uploads.length}/`, + }, + { status: 201 }, + ); + }), + http.post( + "*/api/0/organizations/:org/issues/:issueId/notes/", + async ({ request }) => { + postedText = ((await request.json()) as { text: unknown }).text; + return HttpResponse.json({ + id: "activity-2", + commentId: "comment-2", + type: "note", + user: { name: "Jane Developer" }, + dateCreated: "2025-04-14T12:34:56.000Z", + data: { text: postedText }, + }); + }, + ), + ); + + const result = await addIssueNote.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + issueId: "CLOUDFLARE-MCP-41", + text: "Screen recording of the crash.", + attachmentPaths: ["/tmp/repro.mp4", "/tmp/take2.mov"], + }, + { + ...context, + readLocalFile: localFiles({ + "/tmp/repro.mp4": { name: "repro.mp4", data: MP4 }, + "/tmp/take2.mov": { name: "take2.mov", data: MP4 }, + }), + }, + ); + + expect(uploads).toEqual([ + { name: "repro.mp4", type: "video/mp4", size: MP4.length }, + { name: "take2.mov", type: "video/quicktime", size: MP4.length }, + ]); + expect(postedText).toBe( + "Screen recording of the crash.\n" + + "[repro.mp4](/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/1/)\n" + + "[take2.mov](/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/2/)", + ); + expect(getStructuredContent(result)).toMatchInlineSnapshot(` + { + "issueId": "CLOUDFLARE-MCP-41", + "issueUrl": "https://sentry-mcp-evals.sentry.io/issues/CLOUDFLARE-MCP-41", + "note": { + "attachments": [ + { + "id": "1", + "name": "repro.mp4", + "url": "https://sentry.io/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/1/", + }, + { + "id": "2", + "name": "take2.mov", + "url": "https://sentry.io/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/2/", + }, + ], + "author": "Jane Developer", + "dateCreated": "2025-04-14T12:34:56.000Z", + "id": "comment-2", + "text": "Screen recording of the crash. + [repro.mp4](/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/1/) + [take2.mov](/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/2/)", + "type": "note", + }, + "organizationSlug": "sentry-mcp-evals", + } + `); + }); + + it("refuses files that are not videos before uploading anything", async () => { + let uploaded = false; + mswServer.use( + http.post(ATTACHMENTS_PATH, () => { + uploaded = true; + return HttpResponse.json({}, { status: 201 }); + }), + ); + + await expect( + addIssueNote.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + issueId: "CLOUDFLARE-MCP-41", + text: "Recording attached.", + attachmentPaths: ["/tmp/repro.mp4", "/home/me/.ssh/id_rsa.mp4"], + }, + { + ...context, + readLocalFile: localFiles({ + "/tmp/repro.mp4": { name: "repro.mp4", data: MP4 }, + "/home/me/.ssh/id_rsa.mp4": { + name: "id_rsa.mp4", + data: new TextEncoder().encode("-----BEGIN OPENSSH PRIVATE KEY"), + }, + }), + }, + ), + ).rejects.toThrow("id_rsa.mp4 is not a supported video"); + expect(uploaded).toBe(false); + }); + + it("explains that the hosted server cannot attach local videos", async () => { + await expect( + addIssueNote.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + issueId: "CLOUDFLARE-MCP-41", + text: "Recording attached.", + attachmentPaths: ["/tmp/repro.mp4"], + }, + context, + ), + ).rejects.toThrow(UserInputError); + }); + + it("surfaces Sentry's size limit when an upload is too large", async () => { + mswServer.use( + http.post(ATTACHMENTS_PATH, () => + HttpResponse.json( + { detail: "File is too large. The maximum size is 100 MB." }, + { status: 413 }, + ), + ), + ); + + await expect( + addIssueNote.handler( + { + organizationSlug: "sentry-mcp-evals", + regionUrl: null, + issueId: "CLOUDFLARE-MCP-41", + text: "Recording attached.", + attachmentPaths: ["/tmp/repro.mp4"], + }, + { + ...context, + readLocalFile: localFiles({ + "/tmp/repro.mp4": { name: "repro.mp4", data: MP4 }, + }), + }, + ), + ).rejects.toThrow("File is too large. The maximum size is 100 MB."); + }); }); diff --git a/packages/mcp-core/src/tools/catalog/add-issue-note.ts b/packages/mcp-core/src/tools/catalog/add-issue-note.ts index 726a8fea7c..90ec0f3881 100644 --- a/packages/mcp-core/src/tools/catalog/add-issue-note.ts +++ b/packages/mcp-core/src/tools/catalog/add-issue-note.ts @@ -1,4 +1,13 @@ import { z } from "zod"; +import type { IssueCommentAttachment } from "../../api-client/types"; +import { + appendCommentAttachments, + COMMENT_ATTACHMENT_EXTENSIONS, + commentAttachmentContentType, + commentAttachmentPath, + parseCommentAttachments, +} from "../../comment-attachments"; +import { UserInputError } from "../../errors"; import type { IssueComment } from "../../api-client/types"; import { apiServiceFromContext } from "../../internal/tool-helpers/api"; import { defineTool } from "../../internal/tool-helpers/define"; @@ -14,7 +23,7 @@ import { ParamRegionUrl, } from "../../schema"; import { setTargetTagsAndAttributes } from "../../telem/scope"; -import type { ServerContext } from "../../types"; +import type { LocalFile, LocalFileReader, ServerContext } from "../../types"; import { formatDate, formatId, readString } from "./support/api-formatting"; import { formatActivityAuthor } from "./support/activity-formatting"; @@ -28,16 +37,65 @@ export const addIssueNoteOutputSchema = z.object({ author: z.string(), dateCreated: z.string().nullable(), text: z.string().nullable(), + attachments: z + .array(z.object({ id: z.string(), name: z.string(), url: z.string() })) + .describe("Videos uploaded with the note and linked from its text."), }), }); -function mapNote(comment: IssueComment) { +/** Most videos one note can carry. */ +const MAX_ATTACHMENTS = 5; + +/** + * Reads each path and checks it is a video before anything is uploaded, so a + * bad path never leaves a half-uploaded note. + */ +async function readVideos( + paths: readonly string[], + readLocalFile: LocalFileReader | undefined, +) { + if (!readLocalFile) { + throw new UserInputError( + "Attaching videos needs the local MCP server (`sentry mcp`), which can read files on this machine. This server cannot.", + ); + } + return await Promise.all( + paths.map(async (path) => { + let file: LocalFile; + try { + file = await readLocalFile(path); + } catch (error) { + throw new UserInputError( + `Could not read ${path}: ${error instanceof Error ? error.message : String(error)}`, + ); + } + const contentType = commentAttachmentContentType(file.name, file.data); + if (!contentType) { + throw new UserInputError( + `${file.name} is not a supported video. Attach ${COMMENT_ATTACHMENT_EXTENSIONS.join(", ")} files.`, + ); + } + return { ...file, contentType }; + }), + ); +} + +function mapNote( + comment: IssueComment, + attachmentUrl: (attachmentId: string) => string, +) { + const text = comment.data ? readString(comment.data, "text") : null; return { id: formatId(comment.commentId ?? comment.id), type: comment.type ?? "note", author: formatActivityAuthor(comment, "current user"), dateCreated: formatDate(comment.dateCreated), - text: comment.data ? readString(comment.data, "text") : null, + text, + attachments: parseCommentAttachments(text).map((link) => ({ + id: link.id, + name: link.name, + url: attachmentUrl(link.id), + })), }; } @@ -58,7 +116,16 @@ export default defineTool({ .trim() .min(1) .max(4096) - .describe("The comment text, posted as is."), + .describe( + "The comment text, posted as is. Links to attached videos are added after it.", + ), + attachmentPaths: z + .array(z.string().trim().min(1)) + .max(MAX_ATTACHMENTS) + .optional() + .describe( + "Local paths of videos to attach (MP4, MOV, WebM or Ogg), such as a screen recording of the bug. Only works when the MCP server runs on the user's machine (`sentry mcp`), and only for files in the directory it was started in. Only attach files the user asked for.", + ), }, annotations: { readOnlyHint: false, @@ -89,17 +156,41 @@ export default defineTool({ projectSlug: context.constraints.projectSlug, }); + const videos = params.attachmentPaths?.length + ? await readVideos(params.attachmentPaths, context.readLocalFile) + : []; + const uploaded: IssueCommentAttachment[] = []; + for (const video of videos) { + uploaded.push( + await apiService.uploadIssueCommentAttachment({ + organizationSlug: parsed.organizationSlug, + issueId: parsed.issueId, + fileName: video.name, + contentType: video.contentType, + data: video.data, + }), + ); + } + const comment = await apiService.createIssueComment({ organizationSlug: parsed.organizationSlug, issueId: parsed.issueId, - text: params.text, + text: appendCommentAttachments(params.text, uploaded), }); return structuredResult({ organizationSlug: parsed.organizationSlug, issueId: parsed.issueId, issueUrl: apiService.getIssueUrl(parsed.organizationSlug, parsed.issueId), - note: mapNote(comment), + note: mapNote(comment, (attachmentId) => + apiService.getAbsoluteApiUrl( + commentAttachmentPath( + parsed.organizationSlug, + parsed.issueId, + attachmentId, + ), + ), + ), }); }, }); diff --git a/packages/mcp-core/src/tools/catalog/get-issue-activity.test.ts b/packages/mcp-core/src/tools/catalog/get-issue-activity.test.ts index c9ee784ade..b8cf73be07 100644 --- a/packages/mcp-core/src/tools/catalog/get-issue-activity.test.ts +++ b/packages/mcp-core/src/tools/catalog/get-issue-activity.test.ts @@ -94,6 +94,59 @@ describe("get_issue_activity", () => { `); }); + it("lists videos attached to comments", async () => { + const path = + "/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/7/"; + mockActivity({ + id: "100", + type: "note", + user: { name: "Jane Developer" }, + dateCreated: "2025-04-14T12:34:56.000Z", + data: { + text: `Crash on save\n[repro.mp4](${path})\n[docs](https://docs.sentry.io/)`, + }, + }); + + const result = await getIssueActivity.handler(params, context); + + const structuredContent = getStructuredContent(result); + expect(getIssueActivityOutputSchema.parse(structuredContent)).toEqual( + structuredContent, + ); + expect( + (structuredContent as { comments: Array<{ attachments?: unknown }> }) + .comments[0]?.attachments, + ).toEqual([ + { id: "7", name: "repro.mp4", url: `https://sentry.io${path}` }, + ]); + }); + + it("builds attachment URLs from the issue being read", async () => { + mockActivity({ + id: "101", + type: "note", + user: { name: "Mallory" }, + dateCreated: "2025-04-14T12:34:56.000Z", + data: { + text: "[a.mp4](/api/0/organizations/other-org/issues/999/comment-attachments/7/)", + }, + }); + + const result = await getIssueActivity.handler(params, context); + + expect( + getStructuredContent<{ comments: Array<{ attachments?: unknown }> }>( + result, + ).comments[0]?.attachments, + ).toEqual([ + { + id: "7", + name: "a.mp4", + url: "https://sentry.io/api/0/organizations/sentry-mcp-evals/issues/CLOUDFLARE-MCP-41/comment-attachments/7/", + }, + ]); + }); + it("returns null comments when comments are not requested", async () => { const result = await getIssueActivity.handler( { ...params, includeComments: false }, diff --git a/packages/mcp-core/src/tools/catalog/get-issue-activity.ts b/packages/mcp-core/src/tools/catalog/get-issue-activity.ts index a353cb9329..8b3874d62e 100644 --- a/packages/mcp-core/src/tools/catalog/get-issue-activity.ts +++ b/packages/mcp-core/src/tools/catalog/get-issue-activity.ts @@ -1,5 +1,9 @@ import { z } from "zod"; import type { IssueActivity, IssueComment } from "../../api-client/types"; +import { + commentAttachmentPath, + parseCommentAttachments, +} from "../../comment-attachments"; import { apiServiceFromContext } from "../../internal/tool-helpers/api"; import { defineTool } from "../../internal/tool-helpers/define"; import { @@ -54,6 +58,18 @@ const issueActivityEntrySchema = z.object({ .nullable() .describe("Set when the comment ID differs from the activity ID."), text: z.string().nullable(), + attachments: z + .array( + z.object({ + id: z.string(), + name: z.string(), + url: z.string().describe("API URL that streams the video."), + }), + ) + .optional() + .describe( + "Videos attached to a comment. Download one with `sentry issue comments --download `.", + ), assignee: z .object({ id: z.string(), @@ -273,6 +289,7 @@ function mapExternalIssue(type: string, data: Record) { function mapActivity( activity: IssueActivity | IssueComment, + attachmentUrl: (attachmentId: string) => string, ): IssueActivityEntry { const text = getActivityText(activity); const commentId = activity.commentId; @@ -287,6 +304,14 @@ function mapActivity( : null, text, }; + const attachments = parseCommentAttachments(text); + if (attachments.length > 0) { + entry.attachments = attachments.map((link) => ({ + id: link.id, + name: link.name, + url: attachmentUrl(link.id), + })); + } const data = activity.data; if (text || !isPlainObject(data) || Object.keys(data).length === 0) { @@ -323,7 +348,7 @@ export default defineTool({ skills: ["inspect", "triage"], requiredScopes: ["event:read"], description: - "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when.", + "Get the activity feed and comments of a Sentry issue: who resolved, ignored, assigned, or commented on it, and when, plus any videos attached to comments.", inputSchema: { organizationSlug: ParamOrganizationSlug.optional(), regionUrl: ParamRegionUrl.nullable().default(null), @@ -375,13 +400,23 @@ export default defineTool({ : Promise.resolve([]), ]); + const toEntry = (item: IssueActivity | IssueComment) => + mapActivity(item, (attachmentId) => + apiService.getAbsoluteApiUrl( + commentAttachmentPath( + parsed.organizationSlug, + parsed.issueId, + attachmentId, + ), + ), + ); return structuredResult({ organizationSlug: parsed.organizationSlug, issueId: parsed.issueId, issueUrl: apiService.getIssueUrl(parsed.organizationSlug, parsed.issueId), - activity: activity.slice(0, params.limit).map(mapActivity), + activity: activity.slice(0, params.limit).map(toEntry), comments: params.includeComments - ? comments.slice(0, params.limit).map(mapActivity) + ? comments.slice(0, params.limit).map(toEntry) : null, }); }, diff --git a/packages/mcp-core/src/types.ts b/packages/mcp-core/src/types.ts index 885a6dc308..f1d72fb0ce 100644 --- a/packages/mcp-core/src/types.ts +++ b/packages/mcp-core/src/types.ts @@ -77,6 +77,21 @@ export type CredentialRouter = { list(): Promise; }; +/** A file read from the machine the MCP server runs on. */ +export type LocalFile = { + /** File name without its directory, e.g. `repro.mp4`. */ + name: string; + data: Uint8Array; +}; + +/** + * Reads a local file the user named in a tool call. Only hosts that run on the + * user's machine (the CLI's stdio server) provide one; the hosted server has + * no local files. Paths come from the model, so a host should confine reads + * to a directory the user chose (the CLI uses its working directory). + */ +export type LocalFileReader = (path: string) => Promise; + export type ServerContext = { sentryHost?: string; sentryProtocol?: SentryProtocol; @@ -119,6 +134,11 @@ export type ServerContext = { * default credential's token. */ credentialRouter?: CredentialRouter; + /** + * Reads local files for tools that upload them, such as videos attached to + * issue comments. Unset on hosts without local file access. + */ + readLocalFile?: LocalFileReader; /** * Aborts when the MCP client cancels the tool call. Set only on a per-call * copy of the context (see `withCallSignal`), never on the session context.