⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(api): let MCP assistants open and view attachment images (#431)
Sinming9a030c2d3026
diff --git a/apps/api/src/mcp/__tests__/integration/attachments.test.ts b/apps/api/src/mcp/__tests__/integration/attachments.test.tsnew file mode 100644index 00000000..db07eaf5--- /dev/null+++ b/apps/api/src/mcp/__tests__/integration/attachments.test.ts@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { CallToolResultSchema, type CallToolRequest } from '@modelcontextprotocol/sdk/types.js';+import { auth } from '@repo/auth';+import { app, authedApi } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';+import { buildMcpServer } from '../../server';++// An assistant reads attachments through MCP: every url it is handed is the api's+// public download route, and an image comes back as an image it can look at. The+// stored text keeps the web's /media paths. Needs the object store (MinIO), like the+// attachments tests.++const API = (process.env.API_URL ?? '').replace(/\/+$/, '');+const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);+const IMAGE_BLOCK = {+ type: 'image' as const,+ data: Buffer.from(PNG).toString('base64'),+ mimeType: 'image/png',+};+const clients: Client[] = [];++async function callTool(client: Client, params: CallToolRequest['params']) {+ return CallToolResultSchema.parse(await client.callTool(params));+}++// The text block an image tool puts before its images.+function named(result: Awaited<ReturnType<typeof callTool>>) {+ const first = result.content[0];+ return first.type === 'text' ? JSON.parse(first.text) : null;+}++async function connect(userId: string) {+ const { key } = await auth.api.createApiKey({ body: { userId, name: 'mcp-attachments' } });+ const server = await buildMcpServer(app, { kind: 'api-key', apiKey: key }, userId);+ const client = new Client({ name: 'mcp-attachments-test', version: '1.0.0' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ await client.listTools();+ clients.push(client);+ return client;+}++async function setup() {+ const owner = await signUpTestUser();+ const asOwner = authedApi(owner.cookie);+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });+ const view = await asOwner.projects({ projectKey: 'MKT' }).get();+ const issue = await asOwner+ .projects({ projectKey: 'MKT' })+ .issues.post({ columnId: view.data!.columns[0].id, title: 'Task' });+ const issueId = issue.data!.id;+ const image = await asOwner.issues({ issueId }).attachments.post({+ file: new File([PNG], 'shot.png', { type: 'image/png' }),+ });+ const note = await asOwner.issues({ issueId }).attachments.post({+ file: new File(['hello'], 'note.txt', { type: 'text/plain' }),+ });+ const client = await connect(owner.userId);+ return { asOwner, client, issueId, imageId: image.data!.id, noteId: note.data!.id };+}++describe('MCP attachments', () => {+ beforeEach(resetDb);+ afterEach(async () => {+ await Promise.all(clients.splice(0).map((client) => client.close()));+ });++ it('hands out the api download url and stores the web path', async () => {+ const { asOwner, client, issueId, imageId, noteId } = await setup();+ await asOwner+ .issues({ issueId })+ .patch({ description: `` });++ const issue = await callTool(client, { name: 'get_issue', arguments: { issueId } });+ expect(issue.structuredContent).toMatchObject({+ ok: true,+ data: { description: `` },+ });++ const list = await callTool(client, { name: 'list_attachments', arguments: { issueId } });+ const urls = (list.structuredContent?.data as { url: string }[]).map((a) => a.url);+ expect(urls.sort()).toEqual(+ [`${API}/attachments/${imageId}/raw`, `${API}/attachments/${noteId}/raw`].sort(),+ );++ const updated = await callTool(client, {+ name: 'update_issue',+ arguments: { issueId, description: `Before\n\n` },+ });+ expect(updated.isError).toBe(false);+ const stored = await asOwner.issues({ issueId }).get();+ expect(stored.data!.description).toBe(`Before\n\n`);+ });++ it('shows the images of an issue and lists the other files with their urls', async () => {+ const { client, issueId, imageId, noteId } = await setup();+ const listed = await client.listTools();+ const viewTool = listed.tools.find((tool) => tool.name === 'view_issue_images');+ expect(viewTool?.outputSchema).toBeUndefined();++ const result = await callTool(client, { name: 'view_issue_images', arguments: { issueId } });+ expect(result.isError).toBeFalsy();+ expect(result.structuredContent).toBeUndefined();+ expect(result.content).toEqual([{ type: 'text', text: expect.any(String) }, IMAGE_BLOCK]);+ expect(named(result)).toMatchObject({+ images: [{ id: imageId, filename: 'shot.png', contentType: 'image/png' }],+ others: [{ id: noteId, url: `${API}/attachments/${noteId}/raw` }],+ });+ });++ it('shows one image given the url a result carries, or its id', async () => {+ const { client, imageId, noteId } = await setup();++ for (const attachment of [`${API}/attachments/${imageId}/raw`, imageId]) {+ const result = await callTool(client, { name: 'view_attachment', arguments: { attachment } });+ expect(result.content).toEqual([{ type: 'text', text: expect.any(String) }, IMAGE_BLOCK]);+ }++ const note = await callTool(client, {+ name: 'view_attachment',+ arguments: { attachment: `${API}/attachments/${noteId}/raw` },+ });+ expect(note.content).toHaveLength(1);+ expect(named(note)).toMatchObject({+ images: [],+ others: [{ id: noteId, url: `${API}/attachments/${noteId}/raw` }],+ });++ const missing = await callTool(client, {+ name: 'view_attachment',+ arguments: { attachment: 'not an attachment' },+ });+ expect(missing.isError).toBe(true);+ expect(missing.structuredContent).toMatchObject({ ok: false, status: 404 });+ });++ it('does the same for an initiative', async () => {+ const { asOwner, client } = await setup();+ const created = await asOwner+ .projects({ projectKey: 'MKT' })+ .initiatives.post({ title: 'Q3 Launch' });+ const initiativeId = created.data!.id;+ const uploaded = await asOwner.initiatives({ initiativeId }).attachments.post({+ file: new File([PNG], 'plan.png', { type: 'image/png' }),+ });+ const publicId = uploaded.data!.id;++ const list = await callTool(client, {+ name: 'list_initiative_attachments',+ arguments: { initiativeId },+ });+ expect(list.structuredContent).toMatchObject({+ ok: true,+ data: [{ id: publicId, url: `${API}/initiative-attachments/${publicId}/raw` }],+ });++ const all = await callTool(client, {+ name: 'view_initiative_images',+ arguments: { initiativeId },+ });+ expect(all.content).toEqual([{ type: 'text', text: expect.any(String) }, IMAGE_BLOCK]);+ expect(named(all)).toMatchObject({ images: [{ id: publicId }], others: [] });++ const one = await callTool(client, {+ name: 'view_attachment',+ arguments: { attachment: `${API}/initiative-attachments/${publicId}/raw` },+ });+ expect(one.content).toEqual([{ type: 'text', text: expect.any(String) }, IMAGE_BLOCK]);+ });++ it('refuses an image the caller cannot read', async () => {+ const { imageId } = await setup();+ const outsider = await signUpTestUser();+ const client = await connect(outsider.userId);++ const result = await callTool(client, {+ name: 'view_attachment',+ arguments: { attachment: imageId },+ });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({ ok: false, status: 403 });+ });+});diff --git a/apps/api/src/mcp/__tests__/integration/structured-results.test.ts b/apps/api/src/mcp/__tests__/integration/structured-results.test.tsindex 35bb2064..7e81cca6 100644--- a/apps/api/src/mcp/__tests__/integration/structured-results.test.ts+++ b/apps/api/src/mcp/__tests__/integration/structured-results.test.ts@@ -36,7 +36,15 @@ describe('MCP structured results through the SDK client', () => {const client = await connect(user.userId);const listed = await client.listTools();expect(listed.tools.length).toBeGreaterThan(0);- expect(listed.tools.every((tool) => tool.outputSchema?.type === 'object')).toBe(true);+ const withoutSchema = listed.tools.filter((tool) => tool.outputSchema === undefined);+ expect(withoutSchema.map((tool) => tool.name).sort()).toEqual([+ 'view_attachment',+ 'view_initiative_images',+ 'view_issue_images',+ ]);+ expect(+ listed.tools.every((tool) => !tool.outputSchema || tool.outputSchema.type === 'object'),+ ).toBe(true);const created = await callTool(client, {name: 'create_project',diff --git a/apps/api/src/mcp/__tests__/unit/attachment-urls.test.ts b/apps/api/src/mcp/__tests__/unit/attachment-urls.test.tsnew file mode 100644index 00000000..7e7e0543--- /dev/null+++ b/apps/api/src/mcp/__tests__/unit/attachment-urls.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'bun:test';+import { Elysia, t } from 'elysia';+import { withPublicAttachmentUrls, withStoredAttachmentUrls } from '../../attachment-urls';+import { dispatchTool } from '../../dispatch';+import { mcpTool, routeTools } from '../../generate';++const API = (process.env.API_URL ?? '').replace(/\/+$/, '');+const ID = '0b5c3a52-3f6e-4a4b-9b7f-5d0e8c1a2f34';++describe('withPublicAttachmentUrls', () => {+ it('points the web and api paths of an issue or initiative attachment at the api', () => {+ const body = JSON.stringify({+ description: `\n<video src="/media/initiative-attachments/${ID}/raw"></video>`,+ url: `/attachments/${ID}/raw`,+ });+ expect(JSON.parse(withPublicAttachmentUrls(body))).toEqual({+ description: `\n<video src="${API}/initiative-attachments/${ID}/raw"></video>`,+ url: `${API}/attachments/${ID}/raw`,+ });+ });++ it('reads a path at the start of a line inside a JSON string', () => {+ const body = JSON.stringify({ description: `see below\n/media/attachments/${ID}/raw` });+ expect(JSON.parse(withPublicAttachmentUrls(body)).description).toBe(+ `see below\n${API}/attachments/${ID}/raw`,+ );+ });++ it('keeps the query of a download link', () => {+ expect(withPublicAttachmentUrls(`(/attachments/${ID}/raw?download=1)`)).toBe(+ `(${API}/attachments/${ID}/raw?download=1)`,+ );+ });++ it('leaves absolute urls, document assets and chat files alone', () => {+ const text = [+ `(https://web.example/media/attachments/${ID}/raw)`,+ `(https://api.example/attachments/${ID}/raw)`,+ `(/protected-media/projects/MKT/documents/1/assets/${ID}/raw)`,+ `(/projects/MKT/documents/1/assets/${ID}/raw)`,+ `(/media/chat-attachments/${ID}/raw)`,+ ].join(' ');+ expect(withPublicAttachmentUrls(text)).toBe(text);+ });+});++describe('withStoredAttachmentUrls', () => {+ it('writes the web path back into text', () => {+ expect(+ withStoredAttachmentUrls({+ description: ``,+ fields: [{ value: `[b](${API}/initiative-attachments/${ID}/raw)` }],+ }),+ ).toEqual({+ description: ``,+ fields: [{ value: `[b](/media/initiative-attachments/${ID}/raw)` }],+ });+ });++ it('writes the web path back into text that starts with a word and a colon', () => {+ expect(+ withStoredAttachmentUrls({ description: `Steps:\n` }),+ ).toEqual({ description: `Steps:\n` });+ });++ it('keeps a value that is only a url, and non-string values', () => {+ const args = { url: `${API}/attachments/${ID}/raw`, issueId: 7, done: false, note: null };+ expect(withStoredAttachmentUrls(args)).toEqual(args);+ });+});++describe('dispatchTool', () => {+ it('stores the web path and answers with the api url', async () => {+ let received: unknown;+ const app = new Elysia().post(+ '/echo',+ ({ body }) => {+ received = body;+ return body;+ },+ {+ body: t.Object({ description: t.String() }),+ detail: { summary: 'Echo', ...mcpTool('echo') },+ },+ );+ const description = ``;+ const result = await dispatchTool(+ app,+ routeTools(app)[0]!,+ { description },+ { kind: 'api-key', apiKey: 'unused' },+ { viaMcpEndpoint: true },+ );+ expect(received).toEqual({ description: `` });+ expect(JSON.parse(result.text)).toEqual({ description });+ });+});diff --git a/apps/api/src/mcp/attachment-urls.ts b/apps/api/src/mcp/attachment-urls.tsnew file mode 100644index 00000000..3d21d1c3--- /dev/null+++ b/apps/api/src/mcp/attachment-urls.ts@@ -0,0 +1,37 @@+// Text stores an issue or initiative attachment as a path on the web, which serves it+// through its own /media route. An assistant reaches the api, not the web, so a tool+// result carries the api's public download url, computed on each call, and a call's+// arguments get the stored path back. Document assets need a session and keep theirs.++const ATTACHMENT_PATH = '/(?:initiative-)?attachments/[0-9a-f-]{36}/raw';++// A relative path starts a JSON string, a markdown link target or an HTML attribute;+// `\n` is a newline escaped inside a JSON string. Anything else before the slash is+// the host or path of an absolute url.+const RELATIVE = new RegExp(`(?<=^|[\\s"'(=]|\\\\[nrt])(?:/media)?(${ATTACHMENT_PATH})`, 'gi');++function apiOrigin(): string {+ return (process.env.API_URL ?? '').replace(/\/+$/, '');+}++export function withPublicAttachmentUrls(text: string): string {+ const origin = apiOrigin();+ return text.replace(RELATIVE, (_, path: string) => `${origin}${path}`);+}++export function withStoredAttachmentUrls(args: Record<string, unknown>): Record<string, unknown> {+ const origin = apiOrigin().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const absolute = new RegExp(`${origin}(${ATTACHMENT_PATH})`, 'gi');+ // A value that is only a url is an address the route fetches, not text it stores.+ const restore = (value: unknown): unknown => {+ if (typeof value === 'string') {+ return /^https?:\/\/\S+$/.test(value) ? value : value.replace(absolute, '/media$1');+ }+ if (Array.isArray(value)) return value.map(restore);+ if (value !== null && typeof value === 'object') {+ return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, restore(v)]));+ }+ return value;+ };+ return restore(args) as Record<string, unknown>;+}diff --git a/apps/api/src/mcp/dispatch.ts b/apps/api/src/mcp/dispatch.tsindex d09bc01b..83b902ae 100644--- a/apps/api/src/mcp/dispatch.ts+++ b/apps/api/src/mcp/dispatch.ts@@ -3,6 +3,7 @@ import type { McpRouteTool } from './generate';import { MCP_LOOPBACK_HEADER, setMcpOAuthToken } from '../shared/mcp-request';import type { McpCredential } from './credential';import { structuredResult, type StructuredResult } from './result';+import { withPublicAttachmentUrls, withStoredAttachmentUrls } from './attachment-urls';// Methods that carry a request body; the rest put their arguments in the query.@@ -29,7 +30,7 @@ export async function dispatchTool(credential: McpCredential,opts: { viaMcpEndpoint: boolean },): Promise<{ text: string; isError: boolean; structuredContent: StructuredResult }> {- const rest: Record<string, unknown> = { ...args };+ const rest = withStoredAttachmentUrls(args);let path = tool.path;for (const name of tool.pathParams) {@@ -63,7 +64,7 @@ export async function dispatchTool(});if (credential.kind === 'oauth') setMcpOAuthToken(request, credential.accessToken);const response = await app.handle(request);- const text = await response.text();+ const text = withPublicAttachmentUrls(await response.text());return {text,isError: response.status >= 400,diff --git a/apps/api/src/mcp/generate.ts b/apps/api/src/mcp/generate.tsindex 1ee8eac1..d418d505 100644--- a/apps/api/src/mcp/generate.ts+++ b/apps/api/src/mcp/generate.ts@@ -40,6 +40,8 @@ export interface McpRouteTool {inputSchema: McpInputSchema;outputSchema: McpOutputSchema;annotations: McpToolAnnotations;+ // Set by mcpImageTool.+ images: boolean;// The cell of the role matrix the route's guard asserts, published by the guard as// `x-permission` on the route's detail. Absent on a route that asks only for// project membership.@@ -67,6 +69,12 @@ export function mcpTool(return { 'x-mcp': { tool, annotations } };}+// Marks a route answering with ViewAttachmentsResponse as an MCP tool whose images+// reach the model as image content, not as base64 text.+export function mcpImageTool(tool: string): { 'x-mcp': { tool: string; images: true } } {+ return { 'x-mcp': { tool, images: true } };+}+// What the HTTP method alone says about a route. A GET only reads; a DELETE// removes and repeats harmlessly; PUT/PATCH replace in place, so repeating one// lands on the same state; POST creates, so it does not.@@ -162,7 +170,7 @@ function generateRouteTools(app: McpApp): McpRouteTool[] {| {summary?: string;description?: string;- 'x-mcp'?: { tool?: string; annotations?: McpToolAnnotations };+ 'x-mcp'?: { tool?: string; annotations?: McpToolAnnotations; images?: boolean };'x-permission'?: Permission;}| undefined;@@ -182,6 +190,7 @@ function generateRouteTools(app: McpApp): McpRouteTool[] {inputSchema: mergeInputSchema(hooks, pathParams),outputSchema: outputSchema(hooks.response),permission: detail?.['x-permission'],+ images: detail?.['x-mcp']?.images === true,// Every tool acts on this tracker's own data and reaches nothing outside it,// so openWorldHint is false throughout; the route may still override it.annotations: {diff --git a/apps/api/src/mcp/instructions.ts b/apps/api/src/mcp/instructions.tsindex 97729290..fad0c24c 100644--- a/apps/api/src/mcp/instructions.ts+++ b/apps/api/src/mcp/instructions.ts@@ -74,6 +74,15 @@ a question someone asked in a comment with add_comment carrying replyToId set tothat comment's id, so the answer reads in the thread rather than at the end of theissue.+## Attachments++An image or file in an issue or initiative, and each entry of list_attachments and+list_initiative_attachments, carries a url that downloads the file without a session.+A url in a result does not show you the picture. To look at the images of an issue,+call view_issue_images (view_initiative_images for an initiative); to look at one+image, call view_attachment with its url. A file can be replaced behind the same url,+so view it again rather than reusing what you saw earlier.+## MentionsA comment or an issue description tags someone by writing @handle inline, whichdiff --git a/apps/api/src/mcp/server.ts b/apps/api/src/mcp/server.tsindex 238a3c2a..6438f817 100644--- a/apps/api/src/mcp/server.ts+++ b/apps/api/src/mcp/server.ts@@ -61,7 +61,7 @@ export async function buildMcpServer(? withoutFields(t.inputSchema, [TEAM_PARAM]): t.inputSchema,annotations: t.annotations,- outputSchema: t.outputSchema,+ outputSchema: t.images ? undefined : t.outputSchema,})),}));@@ -92,8 +92,31 @@ export async function buildMcpServer(const { text, isError, structuredContent } = await dispatchTool(app, tool, args, credential, {viaMcpEndpoint: true,});+ if (tool.images && !isError) return { content: imageContent(text) };return { content: [{ type: 'text', text }], isError, structuredContent };});return server;}++interface ViewedAttachments {+ images: { id: string; filename: string; contentType: string; data: string }[];+ others: unknown[];+}++// The images of an image tool follow a text block that names them in the same order and+// lists the attachments left out. There is no structuredContent (nor an outputSchema to+// require one): Claude Code gives the model structuredContent in place of the text+// block when it is present, and earlier versions dropped the images as well.+function imageContent(text: string) {+ const { images, others } = JSON.parse(text) as ViewedAttachments;+ const named = images.map(({ id, filename, contentType }) => ({ id, filename, contentType }));+ return [+ { type: 'text' as const, text: JSON.stringify({ images: named, others }) },+ ...images.map((image) => ({+ type: 'image' as const,+ data: image.data,+ mimeType: image.contentType,+ })),+ ];+}diff --git a/apps/api/src/modules/attachments/index.ts b/apps/api/src/modules/attachments/index.tsindex 3370fe0e..abdd48b5 100644--- a/apps/api/src/modules/attachments/index.ts+++ b/apps/api/src/modules/attachments/index.ts@@ -1,12 +1,17 @@import { Elysia, t } from 'elysia';import { noContent } from '#shared/http';import { authContext } from '#shared/auth-context';-import { entityGuard } from '#shared/guards';+import { assertMcpAllowed, entityGuard } from '#shared/guards';+import { assertPermission, assertProjectFeature } from '#shared/access';import { HttpError } from '#shared/lib';import { pinnedFetch } from '#shared/net';-import { mcpTool } from '#mcp/generate';+import { mcpImageTool, mcpTool } from '#mcp/generate';import { accessErrors, commonErrors, errors } from '#shared/responses';import { getIssueProjectId } from '#modules/issues/service';+import {+ getInitiativeAttachment,+ getInitiativeAttachmentProjectId,+} from '#modules/initiatives/attachments';import { getStorageSettings, MB } from '@repo/db';import {AttachmentResponse,@@ -16,6 +21,8 @@ import {publicIdParams,rawAttachmentQuery,uploadAttachmentBody,+ viewAttachmentQuery,+ ViewAttachmentsResponse,} from './model';import {createAttachment,@@ -33,12 +40,16 @@ import {deleteAttachmentObject,safeAttachmentFilename,storeAttachmentObject,+ viewAttachments,+ VIEWABLE_IMAGES,} from './storage';+const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;+// Public shape returned to the UI: never exposes the internal serial id or the// object key. `url` is the public, no-auth download route — it can be embedded in// an issue description and fetched by external services.-function attachmentDto(a: AttachmentRow) {+function attachmentDto(a: Omit<AttachmentRow, 'id' | 'issueId'>) {return {id: a.publicId,filename: a.filename,@@ -66,6 +77,30 @@ export const attachmentRoutes = new Elysia({if (!existing) return null;return getIssueProjectId(existing.issueId);}),+ // For /attachments/view, which takes the attachment of an issue or an initiative:+ // the checks entityGuard makes, for whichever of the two it is.+ viewableAttachment: {+ async resolve({ query, user, request }) {+ const id = String(query.attachment ?? '').match(UUID)?.[0];+ if (!id) throw new HttpError(404, 'Attachment not found');+ const issueRow = await getAttachmentByPublicId(id);+ if (issueRow) {+ const projectId = await getIssueProjectId(issueRow.issueId);+ if (projectId == null) throw new HttpError(404, 'Attachment not found');+ await assertPermission(projectId, user, 'work_items', 'read');+ await assertMcpAllowed(projectId, request.headers);+ return { viewed: { row: issueRow, dto: attachmentDto(issueRow) } };+ }+ const row = await getInitiativeAttachment(id);+ const projectId = await getInitiativeAttachmentProjectId(id);+ if (!row || projectId == null) throw new HttpError(404, 'Attachment not found');+ await assertPermission(projectId, user, 'initiatives', 'read');+ await assertProjectFeature(projectId, 'initiatives');+ await assertMcpAllowed(projectId, request.headers);+ const dto = { ...attachmentDto(row), url: `/initiative-attachments/${id}/raw` };+ return { viewed: { row, dto } };+ },+ },}).get('/issues/:issueId/attachments',@@ -281,6 +316,37 @@ export const attachmentRoutes = new Elysia({},)+ .get('/attachments/view', ({ viewed }) => viewAttachments([viewed.row], () => viewed.dto), {+ query: viewAttachmentQuery,+ viewableAttachment: true,+ response: { 200: ViewAttachmentsResponse, ...commonErrors },+ detail: {+ summary: 'View an attachment',+ description:+ 'Look at one image of an issue or an initiative, given the url a result carries ' ++ `for it or its id. Returns ${VIEWABLE_IMAGES}; any other file comes back in ` ++ '`others` with its url.',+ ...mcpImageTool('view_attachment'),+ },+ })++ .get(+ '/issues/:issueId/images',+ async ({ params }) => viewAttachments(await listAttachments(params.issueId), attachmentDto),+ {+ params: issueParams,+ issueAttachment: 'read',+ response: { 200: ViewAttachmentsResponse, ...commonErrors },+ detail: {+ summary: 'View the images of an issue',+ description:+ `Look at the images attached to an issue, by its numeric id: ${VIEWABLE_IMAGES}. ` ++ 'Every other attachment comes back in `others` with its url.',+ ...mcpImageTool('view_issue_images'),+ },+ },+ )+// Public download/preview URL: unauthenticated so it works in <img>/<video>// tags and can be fetched by external services. The publicId is an unguessable// uuid. `?download=1` forces a download instead of inline rendering.diff --git a/apps/api/src/modules/attachments/model.ts b/apps/api/src/modules/attachments/model.tsindex 60866843..c549c963 100644--- a/apps/api/src/modules/attachments/model.ts+++ b/apps/api/src/modules/attachments/model.ts@@ -12,6 +12,23 @@ export const AttachmentResponse = t.Object({export const AttachmentListResponse = t.Array(AttachmentResponse);+// `others` are the attachments not returned as an image, each with the url to fetch it.+export const ViewAttachmentsResponse = t.Object({+ images: t.Array(+ t.Object({+ id: t.String(),+ filename: t.String(),+ contentType: t.String(),+ data: t.String({ description: 'The bytes, base64-encoded.' }),+ }),+ ),+ others: AttachmentListResponse,+});++export const viewAttachmentQuery = t.Object({+ attachment: t.String({ description: "The attachment's url, or its id." }),+});+export const issueParams = t.Object({ issueId: t.Numeric() });// The public id is a UUID column. Validating its format here turns a malformed iddiff --git a/apps/api/src/modules/attachments/storage.ts b/apps/api/src/modules/attachments/storage.tsindex 2a51d04e..f0b16b27 100644--- a/apps/api/src/modules/attachments/storage.ts+++ b/apps/api/src/modules/attachments/storage.ts@@ -120,6 +120,51 @@ export async function deleteAttachmentObject(key: string): Promise<void> {});}+const VIEWABLE_IMAGE = /^image\/(png|jpeg|gif|webp)$/i;+const MAX_IMAGE_MB = 5;+const MAX_IMAGES = 8;+const MAX_VIEW_MB = 10;++export const VIEWABLE_IMAGES = `PNG, JPEG, GIF and WebP images of up to ${MAX_IMAGE_MB} MB, at most ${MAX_IMAGES} images and ${MAX_VIEW_MB} MB per call`;++// The images go into the assistant's context whole, so a call is bounded; an attachment+// left out comes back as its DTO, whose url fetches it.+export async function viewAttachments<+ Row extends {+ publicId: string;+ s3Key: string;+ filename: string;+ contentType: string;+ sizeBytes: number;+ },+ Dto,+>(rows: Row[], dto: (row: Row) => Dto) {+ const images: { id: string; filename: string; contentType: string; data: string }[] = [];+ const others: Dto[] = [];+ let bytes = 0;+ for (const row of rows) {+ const fits =+ VIEWABLE_IMAGE.test(row.contentType) &&+ row.sizeBytes <= MAX_IMAGE_MB * MB &&+ images.length < MAX_IMAGES &&+ bytes + row.sizeBytes <= MAX_VIEW_MB * MB;+ if (!fits) {+ others.push(dto(row));+ continue;+ }+ const object = await getObject(row.s3Key).catch((error) => {+ throw new HttpError(+ 502,+ `Could not read ${row.filename}: ${error instanceof Error ? error.message : String(error)}`,+ );+ });+ const data = Buffer.from(await new Response(object.body).arrayBuffer()).toString('base64');+ images.push({ id: row.publicId, filename: row.filename, contentType: row.contentType, data });+ bytes += row.sizeBytes;+ }+ return { images, others };+}+export function attachmentEtag(s3Key: string): string {return `"${createHash('sha256').update(s3Key).digest('base64url').slice(0, 22)}"`;}diff --git a/apps/api/src/modules/initiatives/index.ts b/apps/api/src/modules/initiatives/index.tsindex 8ba935b0..aec67c37 100644--- a/apps/api/src/modules/initiatives/index.ts+++ b/apps/api/src/modules/initiatives/index.ts@@ -1,5 +1,5 @@import { Elysia, t } from 'elysia';-import { mcpTool } from '#mcp/generate';+import { mcpImageTool, mcpTool } from '#mcp/generate';import { noContent } from '#shared/http';import { guards, entityGuard } from '#shared/guards';import { authContext } from '#shared/auth-context';@@ -14,6 +14,7 @@ import {publicIdParams,rawAttachmentQuery,uploadAttachmentBody,+ ViewAttachmentsResponse,} from '#modules/attachments/model';import {assertAttachmentUploadAllowed,@@ -22,6 +23,8 @@ import {deleteAttachmentObject,safeAttachmentFilename,storeAttachmentObject,+ viewAttachments,+ VIEWABLE_IMAGES,} from '#modules/attachments/storage';import {FeedPageResponse,@@ -277,6 +280,25 @@ export const initiativeRoutes = new Elysia({detail: {summary: 'List initiative attachments',description: "List an initiative's attachments by its numeric id.",+ ...mcpTool('list_initiative_attachments'),+ },+ },+ )++ .get(+ '/initiatives/:initiativeId/images',+ async ({ params }) =>+ viewAttachments(await listInitiativeAttachments(params.initiativeId), attachmentDto),+ {+ params: initiativeParams,+ initiative: 'read',+ response: { 200: ViewAttachmentsResponse, ...commonErrors },+ detail: {+ summary: 'View the images of an initiative',+ description:+ `Look at the images attached to an initiative, by its numeric id: ${VIEWABLE_IMAGES}. ` ++ 'Every other attachment comes back in `others` with its url.',+ ...mcpImageTool('view_initiative_images'),},},)diff --git a/docs/mcp-results.md b/docs/mcp-results.mdindex ed89a93a..3162633e 100644--- a/docs/mcp-results.md+++ b/docs/mcp-results.md@@ -1,10 +1,30 @@# MCP tool results-Every MCP tool result contains an object in `structuredContent`. The existing text block+Every MCP tool result contains an object in `structuredContent`, except a successful call+of an image tool (see below). The existing text blockcontains the original REST response body, including an empty string for HTTP 204. Existingclients can continue reading that text. The internal agent runtime keeps its existing resultformat.+## Attachment urls and images++The body is the REST body with one change: the path of an issue or initiative attachment,+whether the api's `/attachments/<id>/raw` or the web's `/media/attachments/<id>/raw`, is+written as a url on the public api origin (`API_URL`). The url is computed on each call and+is never stored. The arguments of a call get the web path back, so a description an+assistant writes keeps `/media/...`. A string argument that is only a url is passed as it+is. Document assets need a session and keep their paths.++`view_attachment` (one attachment, by its url or id), `view_issue_images` and+`view_initiative_images` return images as `image` content blocks: PNG, JPEG, GIF and+WebP, up to 5 MB each, 8 images and 10 MB per call. A text block comes first and names+the images in order, `{ images: [{ id, filename, contentType }], others: [...] }`, where+`others` holds every attachment left out, with its url. These three tools advertise no+`outputSchema` and a successful call has no `structuredContent`: Claude Code gives the+model `structuredContent` in place of the text block when it is present, which loses the+names and the urls of the attachments left out, and earlier versions dropped the images as+well. A failed call has the error envelope below.+A successful call returns:```json