import type { CallToolResult } from '@modelcontextprotocol/server'; import { ApiError } from '../api/taskstream-api'; /** * Runs a tool and answers with its result as JSON text, or, if the API * refuses it, with an error result the model can read and act on (instead of * a protocol error that aborts the call). */ export async function toolResult( run: () => Promise, ): Promise { try { const result = await run(); return { content: [ { type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result ?? { ok: true }, null, 2), }, ], }; } catch (error) { if (!(error instanceof ApiError)) throw error; return { isError: true, content: [ { type: 'text', text: `Error ${error.status}: ${error.message}` }, ], }; } }