⭐️⭐️⭐️ 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): expose structured MCP results and retry metadata (#368)
Ahmad Othman Ammar Adi026b0f5caa24
diff --git a/apps/api/src/mcp/__tests__/integration/structured-results.test.ts b/apps/api/src/mcp/__tests__/integration/structured-results.test.tsnew file mode 100644index 00000000..35bb2064--- /dev/null+++ b/apps/api/src/mcp/__tests__/integration/structured-results.test.ts@@ -0,0 +1,138 @@+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';++const clients: Client[] = [];++async function callTool(client: Client, params: CallToolRequest['params']) {+ return CallToolResultSchema.parse(await client.callTool(params));+}++async function connect(userId: string) {+ const { key } = await auth.api.createApiKey({ body: { userId, name: 'structured-results' } });+ const server = await buildMcpServer(app, { kind: 'api-key', apiKey: key }, userId);+ const client = new Client({ name: 'structured-results-test', version: '1.0.0' });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ clients.push(client);+ return client;+}++describe('MCP structured results through the SDK client', () => {+ beforeEach(resetDb);+ afterEach(async () => {+ await Promise.all(clients.splice(0).map((client) => client.close()));+ });++ it('compiles every advertised output schema and validates object, array, and empty results', async () => {+ const user = await signUpTestUser();+ 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 created = await callTool(client, {+ name: 'create_project',+ arguments: { key: 'RESULT', name: 'Structured results' },+ });+ expect(created.isError).toBe(false);+ expect(created.structuredContent).toMatchObject({+ ok: true,+ status: 201,+ data: { key: 'RESULT', name: 'Structured results' },+ });+ const text = created.content[0];+ expect(text.type).toBe('text');+ if (text.type === 'text')+ expect(JSON.parse(text.text)).toEqual(created.structuredContent?.data);++ const projects = await callTool(client, { name: 'list_projects' });+ expect(projects.structuredContent).toMatchObject({+ ok: true,+ status: 200,+ data: [{ key: 'RESULT' }],+ });++ const deleted = await callTool(client, {+ name: 'delete_project',+ arguments: { projectKey: 'RESULT' },+ });+ expect(deleted.isError).toBe(false);+ expect(deleted.content).toEqual([{ type: 'text', text: '' }]);+ expect(deleted.structuredContent).toEqual({ ok: true, status: 204, data: null });+ });++ it('validates structured validation, conflict, and permission errors without changing their text', async () => {+ const owner = await signUpTestUser();+ const api = authedApi(owner.cookie);+ await api.projects.post({ key: 'PRIVATE', name: 'Private project' });+ const client = await connect(owner.userId);+ await client.listTools();+ for (const [args, status] of [+ [{ key: 'MISSING' }, 400],+ [{ key: 'PRIVATE', name: 'Duplicate' }, 409],+ ] as const) {+ const result = await callTool(client, { name: 'create_project', arguments: args });+ expect(result.isError).toBe(true);+ expect(result.structuredContent).toMatchObject({+ ok: false,+ status,+ error: { code: `HTTP_${status}`, retryable: false, retryAfterSeconds: null },+ });+ const content = result.content[0];+ if (content.type === 'text') {+ expect(JSON.parse(content.text).error).toBe(+ (result.structuredContent?.error as { message: string }).message,+ );+ }+ }++ const outsider = await signUpTestUser();+ const otherClient = await connect(outsider.userId);+ await otherClient.listTools();+ const forbidden = await callTool(otherClient, {+ name: 'get_project',+ arguments: { projectKey: 'PRIVATE' },+ });+ expect(forbidden.isError).toBe(true);+ expect(forbidden.structuredContent).toMatchObject({+ ok: false,+ status: 403,+ error: { code: 'HTTP_403', retryable: false },+ });+ });++ it('returns the same error envelope for missing team arguments and unknown tools', async () => {+ const user = await signUpTestUser();+ await authedApi(user.cookie).teams.post({ name: 'Another team' });+ const client = await connect(user.userId);+ await client.listTools();+ const missing = await callTool(client, { name: 'list_ai_agents' });+ expect(missing.isError).toBe(true);+ expect(missing.structuredContent).toMatchObject({+ ok: false,+ status: 400,+ error: { code: 'HTTP_400', retryable: false },+ });+ expect(missing.content[0]).toMatchObject({+ type: 'text',+ text: expect.stringContaining('teamId'),+ });++ const unknown = await callTool(client, { name: 'unknown_tool' });+ expect(unknown.isError).toBe(true);+ expect(unknown.content).toEqual([{ type: 'text', text: 'Unknown tool: unknown_tool' }]);+ expect(unknown.structuredContent).toMatchObject({+ ok: false,+ status: 404,+ error: { code: 'HTTP_404', retryable: false },+ });+ });+});diff --git a/apps/api/src/mcp/__tests__/unit/result.test.ts b/apps/api/src/mcp/__tests__/unit/result.test.tsnew file mode 100644index 00000000..993a0c8f--- /dev/null+++ b/apps/api/src/mcp/__tests__/unit/result.test.ts@@ -0,0 +1,208 @@+import { describe, expect, it } from 'bun:test';+import { Elysia, t } from 'elysia';+import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';+import type { JsonSchemaType } from '@modelcontextprotocol/sdk/validation/types.js';+import { dispatchTool } from '../../dispatch';+import { mcpTool, routeTools } from '../../generate';+import { outputSchema, structuredResult, toolError } from '../../result';++const validator = new AjvJsonSchemaValidator();++function validate(schema: ReturnType<typeof outputSchema>, value: unknown) {+ return validator.getValidator(schema as JsonSchemaType)(value).valid;+}++describe('structured MCP results', () => {+ it('keeps JSON objects, arrays, and primitives inside the data field', async () => {+ for (const data of [{ id: 1 }, [{ id: 1 }], 42, false, null, 'text']) {+ const response = Response.json(data);+ expect(structuredResult(response, await response.text(), 'GET')).toEqual({+ ok: true,+ status: 200,+ data,+ });+ }+ });++ it('uses null for an empty response and retains non-JSON text', () => {+ expect(structuredResult(new Response(null, { status: 204 }), '', 'DELETE')).toEqual({+ ok: true,+ status: 204,+ data: null,+ });+ for (const text of ['42', 'false', 'null', '"quoted"', ' plain text ']) {+ expect(structuredResult(new Response(text), text, 'GET')).toMatchObject({ data: text });+ }+ expect(+ structuredResult(new Response(''), '', 'GET', outputSchema({ 200: t.String() })),+ ).toMatchObject({ data: '' });+ });++ it('reads JSON media types and retains malformed JSON as text', () => {+ const response = new Response('', { headers: { 'content-type': 'application/problem+json' } });+ expect(structuredResult(response, '{"title":"Example"}', 'GET')).toMatchObject({+ data: { title: 'Example' },+ });+ expect(structuredResult(response, 'not JSON', 'GET')).toMatchObject({ data: 'not JSON' });+ });++ it('preserves domain errors and actionable validation details', async () => {+ const body = { error: 'Column is full', code: 'WIP_LIMIT', columnId: 3, limit: 2 };+ const response = Response.json(body, { status: 409 });+ const result = structuredResult(response, await response.text(), 'PATCH');+ expect(result).toEqual({+ ok: false,+ status: 409,+ error: {+ code: 'WIP_LIMIT',+ message: 'Column is full',+ retryable: false,+ retryAfterSeconds: null,+ details: body,+ },+ });+ expect(validate(outputSchema({ 200: t.Object({ id: t.Number() }) }), result)).toBe(true);+ });++ it('uses stable HTTP codes and safe messages for non-JSON failures', () => {+ const response = new Response('<html>Proxy failure</html>', { status: 502 });+ expect(structuredResult(response, '<html>Proxy failure</html>', 'GET')).toEqual({+ ok: false,+ status: 502,+ error: {+ code: 'HTTP_502',+ message: 'HTTP 502',+ retryable: true,+ retryAfterSeconds: null,+ },+ });+ });++ it('marks only transient failures of safe reads retryable', () => {+ for (const status of [400, 401, 403, 404, 409, 422, 408, 429, 500, 501, 502, 503, 504, 505]) {+ for (const method of ['GET', 'HEAD', 'OPTIONS', 'POST', 'PATCH', 'PUT', 'DELETE']) {+ const result = structuredResult(new Response(null, { status }), '', method);+ expect(result).toMatchObject({+ ok: false,+ status,+ error: {+ code: `HTTP_${status}`,+ retryable:+ ['GET', 'HEAD', 'OPTIONS'].includes(method) &&+ [408, 429, 500, 502, 503, 504].includes(status),+ },+ });+ }+ }+ });++ it('parses Retry-After without exposing other response headers', () => {+ const response = new Response(null, {+ status: 429,+ headers: {+ 'retry-after': '120',+ 'set-cookie': 'sensitive-cookie',+ 'www-authenticate': 'sensitive-challenge',+ 'x-private': 'sensitive-value',+ },+ });+ const result = structuredResult(response, '', 'POST');+ expect(result).toMatchObject({ error: { retryable: false, retryAfterSeconds: 120 } });+ expect(JSON.stringify(result)).not.toContain('sensitive');++ for (const header of ['-1', '1.5', 'Infinity', 'tomorrow', '99999999999999999999']) {+ response.headers.set('retry-after', header);+ expect(structuredResult(response, '', 'GET')).toMatchObject({+ error: { retryAfterSeconds: null },+ });+ }+ response.headers.set('retry-after', new Date(Date.now() + 60_000).toUTCString());+ const dated = structuredResult(response, '', 'GET');+ expect(dated.ok).toBe(false);+ if (!dated.ok) {+ expect(dated.error.retryAfterSeconds).toBeGreaterThanOrEqual(59);+ expect(dated.error.retryAfterSeconds).toBeLessThanOrEqual(60);+ }+ response.headers.set('retry-after', 'Thu, 01 Jan 1970 00:00:00 GMT');+ expect(structuredResult(response, '', 'GET')).toMatchObject({+ error: { retryAfterSeconds: 0 },+ });+ });+});++describe('MCP output schemas', () => {+ it('correlates each declared success status with its response schema and accepts errors', () => {+ const schema = outputSchema({+ 200: t.Array(t.Object({ id: t.Number() })),+ 201: t.Object({ id: t.Number() }),+ 204: t.Void(),+ 400: t.Object({ error: t.String() }),+ });+ expect(validate(schema, { ok: true, status: 200, data: [{ id: 1 }] })).toBe(true);+ expect(validate(schema, { ok: true, status: 201, data: { id: 1 } })).toBe(true);+ expect(validate(schema, { ok: true, status: 204, data: null })).toBe(true);+ expect(validate(schema, { ok: true, status: 200, data: { id: 1 } })).toBe(false);+ expect(validate(schema, { ok: true, status: 201, data: [{ id: 1 }] })).toBe(false);+ expect(validate(schema, { ok: true, status: 204, data: '' })).toBe(false);+ expect(validate(schema, { ok: true, status: 200, data: [{ id: 'wrong' }] })).toBe(false);+ expect(validate(schema, toolError(409, 'Conflict'))).toBe(true);+ expect(validate(schema, toolError(429, 'Slow down'))).toBe(true);+ });++ it('uses a consistent permissive envelope for undeclared or unresolved schemas', () => {+ for (const response of [undefined, 'NamedSchema', { 200: { $ref: '#/definitions/Thing' } }]) {+ const schema = outputSchema(response);+ for (const data of [null, 'text', 42, [], { nested: [1, 2] }]) {+ expect(validate(schema, { ok: true, status: 200, data })).toBe(true);+ }+ expect(validate(schema, { ok: true, status: 202, data: { accepted: true } })).toBe(true);+ expect(validate(schema, toolError(403, 'Forbidden'))).toBe(true);+ }+ });++ it('omits runtime-only schema types and references without breaking unions', () => {+ const schema = outputSchema({+ 200: {+ oneOf: [{ $ref: '#/Unresolved' }, { type: 'Date' }],+ $id: 'runtime-schema',+ },+ });+ expect(JSON.stringify(schema)).not.toContain('$ref');+ expect(JSON.stringify(schema)).not.toContain('$id');+ expect(validate(schema, { ok: true, status: 200, data: '2026-09-09' })).toBe(true);+ });++ it('keeps literal strings and numeric primitives consistent with real Elysia responses', async () => {+ const app = new Elysia()+ .get('/string', () => '42', { response: t.String(), detail: mcpTool('string') })+ .get('/number', () => 42, { response: t.Number(), detail: mcpTool('number') })+ .get('/boolean', () => false, { response: t.Boolean(), detail: mcpTool('boolean') })+ .get('/union', () => 'false', {+ response: t.Union([t.String(), t.Boolean()]),+ detail: mcpTool('union'),+ });+ const expected: Record<string, unknown> = {+ string: '42',+ number: 42,+ boolean: false,+ union: 'false',+ };+ for (const tool of routeTools(app)) {+ const result = await dispatchTool(+ app,+ tool,+ {},+ { kind: 'api-key', apiKey: 'unused' },+ { viaMcpEndpoint: true },+ );+ expect(result.text).toBe(String(expected[tool.name]));+ expect(result.isError).toBe(false);+ expect(result.structuredContent).toEqual({+ ok: true,+ status: 200,+ data: expected[tool.name],+ });+ expect(validate(tool.outputSchema, result.structuredContent)).toBe(true);+ }+ });+});diff --git a/apps/api/src/mcp/dispatch.ts b/apps/api/src/mcp/dispatch.tsindex d5eccc6d..d09bc01b 100644--- a/apps/api/src/mcp/dispatch.ts+++ b/apps/api/src/mcp/dispatch.ts@@ -2,6 +2,7 @@ import type { McpApp } from './types';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';// Methods that carry a request body; the rest put their arguments in the query.@@ -27,7 +28,7 @@ export async function dispatchTool(args: Record<string, unknown>,credential: McpCredential,opts: { viaMcpEndpoint: boolean },-): Promise<{ text: string; isError: boolean }> {+): Promise<{ text: string; isError: boolean; structuredContent: StructuredResult }> {const rest: Record<string, unknown> = { ...args };let path = tool.path;@@ -63,5 +64,9 @@ export async function dispatchTool(if (credential.kind === 'oauth') setMcpOAuthToken(request, credential.accessToken);const response = await app.handle(request);const text = await response.text();- return { text, isError: response.status >= 400 };+ return {+ text,+ isError: response.status >= 400,+ structuredContent: structuredResult(response, text, tool.method, tool.outputSchema),+ };}diff --git a/apps/api/src/mcp/generate.ts b/apps/api/src/mcp/generate.tsindex 785208c3..1ee8eac1 100644--- a/apps/api/src/mcp/generate.ts+++ b/apps/api/src/mcp/generate.ts@@ -1,5 +1,6 @@import type { Permission } from '#shared/guards';import type { McpApp } from './types';+import { outputSchema, type McpOutputSchema } from './result';// Turns the assembled app's routes into MCP tool descriptors. A route opts in by// carrying an `x-mcp` extension in its OpenAPI `detail` (see mcpTool). The route's@@ -37,6 +38,7 @@ export interface McpRouteTool {// DELETE carries one where the deletion needs an argument.hasBody: boolean;inputSchema: McpInputSchema;+ outputSchema: McpOutputSchema;annotations: McpToolAnnotations;// 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@@ -178,6 +180,7 @@ function generateRouteTools(app: McpApp): McpRouteTool[] {pathParams,hasBody: hooks.body != null,inputSchema: mergeInputSchema(hooks, pathParams),+ outputSchema: outputSchema(hooks.response),permission: detail?.['x-permission'],// 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.diff --git a/apps/api/src/mcp/result.ts b/apps/api/src/mcp/result.tsnew file mode 100644index 00000000..b476d57c--- /dev/null+++ b/apps/api/src/mcp/result.ts@@ -0,0 +1,235 @@+type JsonSchema = Record<string, unknown>;++export type StructuredResult =+ | { ok: true; status: number; data: unknown }+ | {+ ok: false;+ status: number;+ error: {+ code: string;+ message: string;+ retryable: boolean;+ retryAfterSeconds: number | null;+ details?: unknown;+ };+ };++export interface McpOutputSchema {+ type: 'object';+ anyOf: JsonSchema[];+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++export function toolError(+ status: number,+ message: string,+): Extract<StructuredResult, { ok: false }> {+ return {+ ok: false,+ status,+ error: { code: `HTTP_${status}`, message, retryable: false, retryAfterSeconds: null },+ };+}++function retryAfterSeconds(value: string | null): number | null {+ if (value === null) return null;+ const trimmed = value.trim();+ if (/^\d+$/.test(trimmed)) {+ const seconds = Number(trimmed);+ return Number.isSafeInteger(seconds) ? seconds : null;+ }+ if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(trimmed)) {+ return null;+ }+ const seconds = Math.max(0, Math.ceil((Date.parse(trimmed) - Date.now()) / 1000));+ return Number.isSafeInteger(seconds) ? seconds : null;+}++function allowsText(schema: unknown): boolean {+ if (!isRecord(schema)) return true;+ if ('const' in schema) return typeof schema.const === 'string';+ if (Array.isArray(schema.enum)) return schema.enum.some((value) => typeof value === 'string');+ if (schema.type) {+ return (+ schema.type === 'string' || (Array.isArray(schema.type) && schema.type.includes('string'))+ );+ }+ if (Array.isArray(schema.anyOf)) return schema.anyOf.some(allowsText);+ if (Array.isArray(schema.allOf)) return schema.allOf.every(allowsText);+ return true;+}++export function structuredResult(+ response: Response,+ text: string,+ method: string,+ schema?: McpOutputSchema,+): StructuredResult {+ const contentType = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();+ const isJson = contentType === 'application/json' || contentType?.endsWith('+json');+ const declared = schema?.anyOf.find((branch) => {+ const properties = branch.properties;+ return (+ isRecord(properties) &&+ isRecord(properties.status) &&+ properties.status.const === response.status+ );+ });+ const properties = declared?.properties;+ const keepsText = isRecord(properties) && allowsText(properties.data);+ let data: unknown = text;+ if (response.status === 204 || (text === '' && !keepsText)) data = null;+ else if (isJson || (declared && !keepsText)) {+ try {+ data = JSON.parse(text);+ } catch {+ // A non-JSON response retains its original text.+ }+ }+ if (response.status < 400) return { ok: true, status: response.status, data };++ const error = toolError(response.status, response.statusText || `HTTP ${response.status}`);+ if (isRecord(data)) {+ if (typeof data.error === 'string') error.error.message = data.error;+ else if (typeof data.message === 'string') error.error.message = data.message;+ if (typeof data.code === 'string' && data.code.length > 0) error.error.code = data.code;+ if (Object.keys(data).some((key) => !['error', 'message', 'code'].includes(key))) {+ error.error.details = data;+ } else if (data.error !== undefined && typeof data.error !== 'string') {+ error.error.details = data;+ }+ } else if (Array.isArray(data)) {+ error.error.details = data;+ }+ error.error.retryable =+ ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase()) &&+ [408, 429, 500, 502, 503, 504].includes(response.status);+ error.error.retryAfterSeconds = retryAfterSeconds(response.headers.get('retry-after'));+ return error;+}++const errorSchema: JsonSchema = {+ type: 'object',+ properties: {+ ok: { const: false },+ status: { type: 'integer', minimum: 400, maximum: 599 },+ error: {+ type: 'object',+ properties: {+ code: { type: 'string' },+ message: { type: 'string' },+ retryable: { type: 'boolean' },+ retryAfterSeconds: { type: ['integer', 'null'], minimum: 0 },+ details: {},+ },+ required: ['code', 'message', 'retryable', 'retryAfterSeconds'],+ additionalProperties: false,+ },+ },+ required: ['ok', 'status', 'error'],+ additionalProperties: false,+};++function successSchema(status: JsonSchema, data: JsonSchema): JsonSchema {+ return {+ type: 'object',+ properties: { ok: { const: true }, status, data },+ required: ['ok', 'status', 'data'],+ additionalProperties: false,+ };+}++// Only JSON Schema keywords are published; TypeBox runtime transforms and unresolved+// references cannot describe the serialized response safely.+function responseSchema(value: unknown): JsonSchema {+ if (!isRecord(value) || '$ref' in value) return {};+ if (value.type === 'void' || value.type === 'undefined') return { type: 'null' };+ const types = ['null', 'boolean', 'object', 'array', 'number', 'integer', 'string'];+ if (+ value.type !== undefined &&+ !(typeof value.type === 'string' && types.includes(value.type)) &&+ !(Array.isArray(value.type) && value.type.every((type) => types.includes(type)))+ ) {+ return {};+ }++ const schema: JsonSchema = {};+ for (const key of [+ 'type',+ 'title',+ 'description',+ 'const',+ 'enum',+ 'minimum',+ 'maximum',+ 'exclusiveMinimum',+ 'exclusiveMaximum',+ 'multipleOf',+ 'minLength',+ 'maxLength',+ 'pattern',+ 'minItems',+ 'maxItems',+ 'uniqueItems',+ 'minProperties',+ 'maxProperties',+ 'required',+ ]) {+ if (value[key] !== undefined) schema[key] = value[key];+ }+ for (const key of ['properties', 'patternProperties']) {+ const fields = value[key];+ if (isRecord(fields)) {+ schema[key] = Object.fromEntries(+ Object.entries(fields).map(([name, field]) => [name, responseSchema(field)]),+ );+ }+ }+ for (const key of ['items', 'additionalProperties']) {+ const field = value[key];+ if (typeof field === 'boolean') schema[key] = field;+ else if (Array.isArray(field)) schema[key] = field.map(responseSchema);+ else if (field !== undefined) schema[key] = responseSchema(field);+ }+ for (const key of ['anyOf', 'oneOf', 'allOf']) {+ const branches = value[key];+ if (Array.isArray(branches)) {+ schema[key === 'oneOf' ? 'anyOf' : key] = branches.map(responseSchema);+ }+ }+ return schema;+}++export function outputSchema(response: unknown): McpOutputSchema {+ const success: [number, unknown][] = [];+ if (isRecord(response)) {+ const statuses = Object.keys(response).filter((key) => /^\d{3}$/.test(key));+ if (statuses.length === 0) success.push([200, response]);+ else {+ for (const status of statuses) {+ if (Number(status) >= 200 && Number(status) < 300) {+ success.push([Number(status), response[status]]);+ }+ }+ }+ }+ const declaredStatuses = success.map(([status]) => status);+ const fallbackStatus: JsonSchema = { type: 'integer', minimum: 200, maximum: 399 };+ if (declaredStatuses.length) fallbackStatus.not = { enum: declaredStatuses };+ return {+ type: 'object',+ anyOf: [+ ...success.map(([status, schema]) =>+ successSchema(+ { const: status },+ status === 204 ? { type: 'null' } : responseSchema(schema),+ ),+ ),+ successSchema(fallbackStatus, {}),+ errorSchema,+ ],+ };+}diff --git a/apps/api/src/mcp/server.ts b/apps/api/src/mcp/server.tsindex d1d08b33..238a3c2a 100644--- a/apps/api/src/mcp/server.ts+++ b/apps/api/src/mcp/server.ts@@ -7,6 +7,7 @@ import { routeTools, withoutFields, type McpRouteTool } from './generate';import { dispatchTool } from './dispatch';import { SERVER_INSTRUCTIONS } from './instructions';import type { McpCredential } from './credential';+import { toolError } from './result';// The path param of every team-scoped route.const TEAM_PARAM = 'teamId';@@ -60,38 +61,38 @@ export async function buildMcpServer(? withoutFields(t.inputSchema, [TEAM_PARAM]): t.inputSchema,annotations: t.annotations,+ outputSchema: t.outputSchema,})),}));server.setRequestHandler(CallToolRequestSchema, async (req) => {const tool = byName.get(req.params.name);if (!tool) {+ const text = `Unknown tool: ${req.params.name}`;return {- content: [{ type: 'text', text: `Unknown tool: ${req.params.name}` }],+ content: [{ type: 'text', text }],isError: true,+ structuredContent: toolError(404, text),};}const args = { ...(req.params.arguments ?? {}) };if (needsTeam(tool)) {if (teamId !== null) args[TEAM_PARAM] = teamId;else if (args[TEAM_PARAM] == null) {+ const text =+ 'teamId is required: no single team follows from your key. Call list_teams and ' ++ 'pass the id of the team to act in.';return {- content: [- {- type: 'text',- text:- 'teamId is required: no single team follows from your key. Call list_teams and ' +- 'pass the id of the team to act in.',- },- ],+ content: [{ type: 'text', text }],isError: true,+ structuredContent: toolError(400, text),};}}- const { text, isError } = await dispatchTool(app, tool, args, credential, {+ const { text, isError, structuredContent } = await dispatchTool(app, tool, args, credential, {viaMcpEndpoint: true,});- return { content: [{ type: 'text', text }], isError };+ return { content: [{ type: 'text', text }], isError, structuredContent };});return server;diff --git a/docs/mcp-results.md b/docs/mcp-results.mdnew file mode 100644index 00000000..ed89a93a--- /dev/null+++ b/docs/mcp-results.md@@ -0,0 +1,61 @@+# MCP tool results++Every MCP tool result contains an object in `structuredContent`. The existing text block+contains the original REST response body, including an empty string for HTTP 204. Existing+clients can continue reading that text. The internal agent runtime keeps its existing result+format.++A successful call returns:++```json+{+ "ok": true,+ "status": 200,+ "data": [{ "id": 12, "key": "ENG", "name": "Engineering" }]+}+```++`data` contains the JSON response, including arrays and primitive values. A non-JSON response+retains its text. HTTP 204 and empty responses without a declared string response use `null`.+Elysia sends numbers and booleans as plain text; a declared response schema lets the adapter+decode those values. A response schema allowing strings keeps non-JSON text as a string,+including values such as `"42"` or `"false"`.++A failed call sets `isError: true` and returns:++```json+{+ "ok": false,+ "status": 429,+ "error": {+ "code": "HTTP_429",+ "message": "Too many requests",+ "retryable": true,+ "retryAfterSeconds": 30+ }+}+```++- `status` is the REST HTTP status. Missing team arguments use 400; unknown tools use 404.+- `code` preserves a domain error code when the API supplies one. Otherwise it is `HTTP_`+ followed by the status number. Clients can branch on this code without parsing the message.+- `message` preserves the API's error message. Non-JSON failures use the HTTP status text+ or `HTTP <status>`.+- `details`, when present, contains additional fields from a JSON error response, such as+ validation information or conflict limits.+- `retryable` is true only for GET, HEAD, or OPTIONS calls returning 408, 429, 500, 502, 503,+ or 504. The adapter performs no retries. Mutations return false because a lost response+ can follow a completed write. Read the current state and reconcile it before repeating+ a mutation.+- `retryAfterSeconds` contains a valid `Retry-After` delay, including an HTTP date converted+ to a nonnegative number of seconds, or `null`. Other HTTP headers are never included.++Each tool advertises an `outputSchema` for this envelope. Declared REST success schemas+describe `data` for their corresponding HTTP statuses. The schema also permits the error+envelope, so SDK clients can validate failed calls. Undeclared statuses and unresolved or+runtime-only schemas use a permissive data schema. JSON Schema formats and runtime metadata+are omitted; the API remains responsible for validating its responses.++This uses the existing SDK's support for+[structured content and output schemas](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content).+It does not change protocol negotiation or the SDK version.