Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Show why a connector tool failed, in the step and to the agent (#133)

Dias950e3e049c13
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c6155a..3084a22 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
> - **Um agente só acorda outro quando precisa.** Quando um agente menciona outro na resposta, o router lê e chama só quem tem algo a fazer: um agradecimento ou um “combinado” não acordam ninguém. Na dúvida, chama.
> - **O app abre fora do instalador mesmo com uma versão estranha.** O atualizador, que nem é usado ali, conferia a versão ao abrir e derrubava o app.
> - **Agentes no Grok.** Um agente pode rodar no Grok CLI, com a assinatura do grok.com, como roda no Cursor CLI. Cada resposta usa uma pasta própria: os seus plugins, skills e hooks não carregam, e só as ferramentas do Tucano ficam à mão.
+> - **Um conector que falha diz por quê.** O passo da resposta mostra o motivo em vermelho, e o agente recebe o mesmo motivo pra explicar, em vez de um ✗ sem nada.
### Added
@@ -22,6 +23,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
### Fixed
+- **A connector tool that fails says why.** The reply's step showed a bare ✗ next to the tool's name, and for some failures the agent got an empty result too. The step now shows the reason under its label (a few lines, all of it on a click), and the agent gets it: a reason only in the structured content or an embedded resource, an MCP error's code and data, a timeout in seconds, a result that doesn't match the tool's schema, or a session that couldn't reconnect. An approved call and a routine's poll say it the same way. Thanks [@rjgdias](https://github.com/rjgdias)! ([#133](https://github.com/eduwxyz/tucano/pull/133))
- **Long conversations stay light while an agent replies.** Each streamed word redrew and re-parsed every message in the list, keeping the window busy on long conversations. Now only the message that changed is drawn again.
- **An agent's browser loads pages on a Linux server that is a desktop PC.** Chrome waited for the desktop's locked keyring before its first page and never got it, so every page hung. On a server it now uses its own cookie store; a desktop keeps the keyring.
- **The server's page opens over plain HTTP on a private address,** such as Tailscale or a home network. It stayed blank: a browser outside a secure context has no `crypto.randomUUID`, which the app calls as it starts. The page now brings a small replacement for it, and one for the copy buttons.
diff --git a/src/core/connectors.ts b/src/core/connectors.ts
index 43fee99..8d115f5 100644
--- a/src/core/connectors.ts
+++ b/src/core/connectors.ts
@@ -7,7 +7,7 @@ import { UnauthorizedError, type OAuthClientProvider } from '@modelcontextprotoc
import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
import { StreamableHTTPClientTransport, StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
-import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
+import { ErrorCode, McpError, type CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js'
import { L } from '../shared/lang'
import { friendly } from '../shared/errors'
@@ -43,12 +43,44 @@ export function connectError(e: unknown): string {
return raw
}
+// The text of a tool's result: its text blocks, the text of embedded resources, and the structured content
+// when that's all there is (a server may put an error's reason only there).
+export function contentText(r: Pick<CallToolResult, 'content' | 'structuredContent'>): string {
+ const text = (r.content ?? [])
+ .map((c) => (c.type === 'text' ? c.text : c.type === 'resource' && 'text' in c.resource ? c.resource.text : `[${c.type}]`))
+ .join('\n')
+ if (text.trim() || !r.structuredContent) return text
+ return JSON.stringify(r.structuredContent)
+}
+
+// Why a tool returned an error: what it said, or that it said nothing (an empty failure would show a bare ✗).
+export function errorReason(r: Pick<CallToolResult, 'content' | 'structuredContent'>): string {
+ return contentText(r).trim() || L('O servidor devolveu um erro sem mensagem.', 'The server returned an error with no message.')
+}
+
+// Why a tool call threw, in words: a timeout says how long it waited, an MCP error keeps the code and the
+// data the server sent with it (the SDK's message leaves the data out).
+export function callError(e: unknown, timeoutMs = CALL_TIMEOUT_MS): string {
+ if (e instanceof McpError) {
+ if (e.code === ErrorCode.RequestTimeout) {
+ const s = Math.round(timeoutMs / 1000)
+ return L(`O servidor não respondeu em ${s} s e a chamada foi cancelada.`, `The server didn't answer in ${s} s, so the call was cancelled.`)
+ }
+ const message = e.message.replace(/^(MCP error -?\d+:\s*)+/, '') // a server's own McpError arrives wrapped twice
+ const data = e.data === undefined || e.data === null ? '' : typeof e.data === 'string' ? e.data : JSON.stringify(e.data)
+ return `${message} (${L('código', 'code')} ${e.code})${data ? `: ${data}` : ''}`
+ }
+ const message = (e instanceof Error ? e.message : String(e)).trim()
+ return message || L('A chamada falhou sem mensagem.', 'The call failed with no message.')
+}
+
export interface ConnectorDeps {
db: Db
secrets: Secrets
emit: (e: CoreEvent) => void
openUrl: (url: string) => void
oauthCallbackUrl: () => string
+ callTimeoutMs?: number // how long a tool call may take; tests shorten it
}
interface Live {
@@ -312,8 +344,9 @@ export class ConnectorManager {
}
// Runs a tool on the real server, reconnecting on demand. Stdio servers that
- // keep failing are marked as having a problem.
+ // keep failing are marked as having a problem. What it throws says why, in words.
async call(id: string, name: string, args: Record<string, unknown>): Promise<CallToolResult> {
+ const timeout = this.deps.callTimeoutMs ?? CALL_TIMEOUT_MS
let l = this.live.get(id)
if (!l?.client) {
await this.connect(id)
@@ -321,18 +354,28 @@ export class ConnectorManager {
}
if (!l?.client) throw new Error(L(`O conector ${this.deps.db.connector(id)?.name ?? id} não está conectado`, `The connector ${this.deps.db.connector(id)?.name ?? id} isn't connected`) + (l?.error ? `: ${l.error}.` : '.'))
try {
- const r = (await l.client.callTool({ name, arguments: args }, undefined, { timeout: CALL_TIMEOUT_MS })) as CallToolResult
+ const r = (await l.client.callTool({ name, arguments: args }, undefined, { timeout })) as CallToolResult
l.failures = 0
return r
} catch (e) {
+ let failure = e
if (staleSession(e)) {
await this.connect(id)
const again = this.live.get(id)?.client
- if (again) return (await again.callTool({ name, arguments: args }, undefined, { timeout: CALL_TIMEOUT_MS })) as CallToolResult
+ if (again) {
+ try {
+ return (await again.callTool({ name, arguments: args }, undefined, { timeout })) as CallToolResult
+ } catch (e2) {
+ failure = e2
+ }
+ } else {
+ const why = this.live.get(id)?.error
+ throw new Error(L('A sessão com o servidor expirou e não deu pra conectar de novo', 'The session with the server expired and it could not connect again') + (why ? `: ${why}` : '.'), { cause: e })
+ }
}
const c = this.deps.db.connector(id)
if (c?.kind === 'stdio' && ++l.failures >= MAX_STDIO_FAILURES) this.setStatus(id, 'error', L(`Falhou ${l.failures} vezes seguidas.`, `Failed ${l.failures} times in a row.`))
- throw e
+ throw new Error(callError(failure, timeout), { cause: failure })
}
}
diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.ts
index f2818ce..a8d3253 100644
--- a/src/core/engines/fake.ts
+++ b/src/core/engines/fake.ts
@@ -63,6 +63,11 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (
const id = Number(/apag\w* a tarefa (\d+)/i.exec(last)![1])
await callTool(turn.mcpUrl, await toolNamed(turn.mcpUrl, 'delete_task'), { id, _motivo: 'Você pediu pra apagar.' })
reply = `Pedi sua aprovação pra apagar a tarefa #${id}.`
+ } else if (turn.mcpUrl && /(?:consulte|run the sql) `([^`]+)`/i.test(last)) {
+ // A SQL connector's tool (Databricks' execute_sql_read_only), to see its steps and errors.
+ const statement = /(?:consulte|run the sql) `([^`]+)`/i.exec(last)![1]!
+ const r = await callTool(turn.mcpUrl, await toolNamed(turn.mcpUrl, 'execute_sql_read_only'), { statement })
+ reply = textOf(r)
} else if (turn.mcpUrl && /rode `([^`]+)`/i.test(last)) {
const r = await callTool(turn.mcpUrl, 'bash', { command: /rode `([^`]+)`/i.exec(last)![1]! })
reply = `Saída:\n\n${textOf(r)}`
diff --git a/src/core/routines.ts b/src/core/routines.ts
index e238399..36d9c33 100644
--- a/src/core/routines.ts
+++ b/src/core/routines.ts
@@ -8,6 +8,7 @@ import { firstSentence } from '../shared/errors'
import type { CoreEvent } from '../shared/rpc'
import { describeSchedule, MAX_AGENT_ROUTINES, nextRun, routineCap, validTime, type Agent, type Connector, type Conversation, type Message, type Routine, type RoutineInput, type Trigger } from '../shared/types'
import type { Db } from './db'
+import { errorReason } from './connectors'
import type { ToolDef } from './gateway'
import type { RoutineEvent } from './runs'
@@ -204,7 +205,7 @@ export class Routines {
if (!tool || !tool.enabled || tool.cls !== 'read') throw new Error(L(`a ferramenta ${t.tool} não está liberada como leitura`, `the tool ${t.tool} isn't enabled for reading`))
const r = await this.deps.connectors.call(t.connectorId, t.tool, t.args)
const text = r.content.map((c) => (c.type === 'text' ? c.text : '')).join('\n')
- if (r.isError) throw new Error(text.slice(0, 200) || L('a ferramenta deu erro', 'the tool returned an error'))
+ if (r.isError) throw new Error(errorReason(r).slice(0, 200))
return { items: eventItems(text), source: `${connector.name} · ${t.tool}` }
}
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 17b8de4..b9207a3 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -24,6 +24,7 @@ import { textResult, type Gateway, type ToolDef } from './gateway'
import { JEV_MODEL, routeJev } from './jev'
import { ROUTER_HISTORY, route, screenHandoff } from './router'
import { allowed, approvalHash, canonical } from './policy'
+import { callError, contentText, errorReason } from './connectors'
const MAX_CONCURRENT = 4
const MAX_TURN_IMAGES = 6 // attached images a reply sees as images; older ones only by name
@@ -41,6 +42,7 @@ const OVER_CALLS_GRACE = 3 // calls refused past the budget before the turn is c
const BUDGET_OVERRUN = 1.3 // past the budget by this much without wrapping up, the turn is cut
const USAGE_ALERT = 0.8
const NARRATION_MAX = 600 // longer text before a tool call is an answer, and stays in the reply
+const STEP_ERROR_MAX = 2_000 // the reason a step failed, as kept on the step
const THOUGHT = (): string => L('Pensou', 'Thought') // the thinking step, closed
export const ASK_USER: ToolDef = {
@@ -107,9 +109,7 @@ const tokenCount = (n: number): string =>
n >= 1_000_000 ? `${(n / 1_000_000).toLocaleString(locale(), { maximumFractionDigits: 1 })} ${L('mi', 'M')}` : `${Math.round(n / 1000).toLocaleString(locale())}${L(' mil', 'k')}`
export function resultText(r: CallToolResult): string {
- const text = r.content
- .map((c) => (c.type === 'text' ? c.text : `[${c.type}]`))
- .join('\n')
+ const text = r.isError ? errorReason(r) : contentText(r)
const bytes = Buffer.from(text, 'utf8')
if (bytes.length <= MAX_RESULT_BYTES) return text
// Cut on a whole character: a split one decodes as U+FFFD at the end.
@@ -1114,19 +1114,24 @@ export class Runner {
flush()
msg.run = { ...msg.run!, steps: [...closeThinking('done', THOUGHT()), step] }
save()
- const finish = (status: 'done' | 'error'): void => {
- msg.run = { ...msg.run!, steps: [...msg.run!.steps.map((s) => (s.id === step.id ? { ...s, status, ms: Date.now() - t0 } : s)), thinking()] }
+ // A failure keeps its reason on the step: a bare ✗ leaves nobody knowing why.
+ const finish = (status: 'done' | 'error', error?: string): void => {
+ if (error) console.warn(`[connector] ${detail} failed: ${error}`)
+ const reason = error ? { error: error.length > STEP_ERROR_MAX ? `${error.slice(0, STEP_ERROR_MAX)}…` : error } : {}
+ msg.run = { ...msg.run!, steps: [...msg.run!.steps.map((s) => (s.id === step.id ? { ...s, status, ms: Date.now() - t0, ...reason } : s)), thinking()] }
stepStarted = Date.now()
save()
}
try {
const { [REASON_PARAM]: _reason, ...toolArgs } = args
const r = await this.deps.connectors!.call(hit.connector.id, current.name, toolArgs)
- finish(r.isError ? 'error' : 'done')
+ if (r.isError) finish('error', errorReason(r))
+ else finish('done')
return clip(r)
} catch (e) {
- finish('error')
- return textResult(L(`A ferramenta falhou: ${e instanceof Error ? e.message : String(e)}`, `The tool failed: ${e instanceof Error ? e.message : String(e)}`), true)
+ const why = callError(e)
+ finish('error', why)
+ return textResult(L(`A ferramenta falhou: ${why}`, `The tool failed: ${why}`), true)
}
}
@@ -1504,7 +1509,7 @@ export class Runner {
try {
const r = await this.deps.connectors!.call(ap.connectorId, ap.tool, ap.args)
ok = !r.isError
- outcome = r.isError ? L('Executou, com erro.', 'Ran, with an error.') : ran
+ outcome = r.isError ? L(`Executou, com erro: ${errorReason(r).slice(0, STEP_ERROR_MAX)}`, `Ran, with an error: ${errorReason(r).slice(0, STEP_ERROR_MAX)}`) : ran
task = L(
`${me} aprovou o seu pedido ${call}. O app executou exatamente essa chamada${r.isError ? ' e ela devolveu um erro' : ''}. Resultado:\n${resultText(r)}\n\nContinue a partir daqui e conte o resultado a ${me}.`,
`${me} approved your request ${call}. The app ran exactly that call${r.isError ? ' and it returned an error' : ''}. Result:\n${resultText(r)}\n\nGo on from here and tell ${me} the result.`
diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index c0b811a..bd1da5a 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -948,14 +948,21 @@ function RunSteps({ message }: { message: Message }): ReactNode {
}
function StepRow({ step }: { step: Step }): ReactNode {
+ const [whole, setWhole] = useState(false)
return (
- <li className={`step step--${step.status}`}>
+ <li className={`step step--${step.status}${step.error ? ' step--why' : ''}`}>
<span className="step__icon">
{step.status === 'running' ? <span className="spinner" /> : <Icon name={step.status === 'done' ? 'check' : 'x'} size={12} />}
</span>
<span className="step__label">{step.label}</span>
{step.note ? <span className="step__note">{step.note}</span> : step.detail && <code className="step__detail">{step.detail}</code>}
{step.ms !== undefined && <span className="step__ms">{duration(step.ms)}</span>}
+ {step.error && (
+ // Why it failed, in the tool's words: a few lines, the whole of it on a click.
+ <span className={`step__error${whole ? ' is-whole' : ''}`} title={whole ? undefined : L('Ver tudo', 'See all')} onClick={() => setWhole(!whole)}>
+ {step.error}
+ </span>
+ )}
</li>
)
}
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css
index c319248..e790083 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -1328,6 +1328,29 @@ h3 {
font-size: 12.5px;
line-height: 1.4;
}
+.step--why {
+ flex-wrap: wrap;
+ row-gap: 2px;
+}
+.step__error {
+ flex-basis: 100%;
+ padding-left: 26px; /* under the label, past the icon */
+ color: var(--danger);
+ font-size: 12px;
+ line-height: 1.4;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ user-select: text;
+ cursor: pointer;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.step__error.is-whole {
+ display: block;
+ cursor: text;
+}
.step__ms {
margin-left: auto;
flex-shrink: 0;
diff --git a/src/shared/types.ts b/src/shared/types.ts
index b317fe4..eadc407 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -138,6 +138,7 @@ export interface Step {
label: string
detail?: string
note?: string // what the agent said while working, before this step's tool call
+ error?: string // why it failed, in the tool's own words
status: StepStatus
ms?: number
}
diff --git a/test/connector-errors.test.ts b/test/connector-errors.test.ts
new file mode 100644
index 0000000..7f1fdd3
--- /dev/null
+++ b/test/connector-errors.test.ts
@@ -0,0 +1,184 @@
+// A connector tool that fails must say why: in the reply's step, where the person sees it, and in the
+// result the agent gets. Through the real pieces (a stdio MCP server, the connector manager, the gateway
+// and the runner); only the model is scripted, calling one tool like a CLI would.
+import { mkdtempSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { Client } from '@modelcontextprotocol/sdk/client/index.js'
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { setLang } from '../src/shared/lang'
+import type { Agent, Message, Settings } from '../src/shared/types'
+import { callError, ConnectorManager, errorReason } from '../src/core/connectors'
+import { Db } from '../src/core/db'
+import { fakeEngine } from '../src/core/engines/fake'
+import type { Engine } from '../src/core/engines/types'
+import { Gateway } from '../src/core/gateway'
+import { Runner } from '../src/core/runs'
+import { plainCipher, Secrets } from '../src/core/secrets'
+
+const sdk = pathToFileURL(resolve('node_modules/@modelcontextprotocol/sdk/dist/esm')).href
+const ready = { installed: true, loggedIn: true }
+
+// A SQL tool like Databricks' that fails in every way a server can: the statement picks the way.
+const SERVER = `const { Server } = await import('${sdk}/server/index.js')
+const { StdioServerTransport } = await import('${sdk}/server/stdio.js')
+const { ListToolsRequestSchema, CallToolRequestSchema, McpError } = await import('${sdk}/types.js')
+const s = new Server({ name: 'sql', version: '1' }, { capabilities: { tools: {} } })
+const input = { type: 'object', properties: { statement: { type: 'string' } }, required: ['statement'] }
+s.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [
+ { name: 'execute_sql_read_only', description: 'Runs a read-only SQL statement.', inputSchema: input, annotations: { readOnlyHint: true } },
+ { name: 'query_typed', description: 'Runs SQL, typed output.', inputSchema: input, annotations: { readOnlyHint: true },
+ outputSchema: { type: 'object', properties: { rows: { type: 'array' } }, required: ['rows'] } }
+] }))
+s.setRequestHandler(CallToolRequestSchema, async (r) => {
+ const q = r.params.arguments.statement
+ if (r.params.name === 'query_typed') return { content: [{ type: 'text', text: '3 rows' }], structuredContent: { row_count: 3 } }
+ if (q === 'structured') return { isError: true, content: [], structuredContent: { error_code: 'RESOURCE_DOES_NOT_EXIST', message: 'Warehouse abc123 is stopped' } }
+ if (q === 'empty') return { isError: true, content: [{ type: 'text', text: ' ' }] }
+ if (q === 'resource') return { isError: true, content: [{ type: 'resource', resource: { uri: 'sql://error', text: 'TABLE_OR_VIEW_NOT_FOUND: main.sales.orders' } }] }
+ if (q === 'throw') throw new McpError(-32603, 'Statement failed', { error_code: 'PERMISSION_DENIED', message: 'User does not have SELECT on main.sales' })
+ if (q === 'slow') await new Promise((ok) => setTimeout(ok, 3000))
+ return { content: [{ type: 'text', text: 'id\\n1\\n2' }] }
+})
+await s.connect(new StdioServerTransport())`
+
+let dir: string
+let db: Db
+let gateway: Gateway
+let connectors: ConnectorManager
+let connectorId: string
+let settings: Settings
+let results: { text: string; isError?: boolean }[]
+
+// A "model" that calls the SQL tool once with the statement in the message, and says what it got.
+function sqlModel(tool = 'execute_sql_read_only'): Engine {
+ return {
+ id: 'claude',
+ async *run(turn) {
+ let reply = 'ok'
+ if (turn.mcpUrl) {
+ const client = new Client({ name: 'scripted', version: '0' })
+ await client.connect(new StreamableHTTPClientTransport(new URL(turn.mcpUrl)))
+ const name = (await client.listTools()).tools.map((t) => t.name).find((t) => t.endsWith(`__${tool}`))!
+ const statement = /`([^`]+)`/.exec(turn.prompt)?.[1] ?? 'select 1'
+ const r = (await client.callTool({ name, arguments: { statement } })) as { content: { type: string; text?: string }[]; isError?: boolean }
+ results.push({ text: r.content.map((c) => c.text ?? '').join('\n'), isError: r.isError })
+ await client.close()
+ reply = 'feito'
+ }
+ yield { type: 'text', delta: reply }
+ yield { type: 'done', text: reply, usage: { inputTokens: 10, cacheReadTokens: 0, outputTokens: 2 } }
+ }
+ }
+}
+
+const agent: () => Agent = () => ({
+ id: 'a1', name: 'Lia', handle: 'lia', role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low',
+ limit: 1_000_000, used: 0, grants: { [connectorId]: 'read' }, memory: 'auto', computer: false, archived: false
+})
+
+async function ask(statement: string, tool?: string): Promise<{ step: NonNullable<Message['run']>['steps'][number]; result: { text: string; isError?: boolean } }> {
+ const runner = new Runner({
+ db,
+ engines: { claude: sqlModel(tool), codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') },
+ settings: async () => settings,
+ emit: () => {},
+ workDir: join(dir, 'work'),
+ gateway,
+ connectors
+ })
+ await runner.send('d1', `rode \`${statement}\``)
+ await runner.idle()
+ const reply = db.messages().filter((m) => m.author.kind === 'agent').at(-1)!
+ const step = reply.run!.steps.find((s) => s.detail?.includes(tool ?? 'execute_sql_read_only'))!
+ return { step, result: results.at(-1)! }
+}
+
+beforeEach(async () => {
+ setLang('en')
+ dir = mkdtempSync(join(tmpdir(), 'tucano-conn-errors-'))
+ db = new Db(join(dir, 'test.db'))
+ results = []
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'en' }
+ gateway = new Gateway()
+ await gateway.start()
+ connectors = new ConnectorManager({ db, secrets: new Secrets(db, plainCipher), emit: () => {}, openUrl: () => {}, oauthCallbackUrl: () => gateway.url('/oauth/callback'), callTimeoutMs: 1000 })
+ const script = join(dir, 'server.mjs')
+ writeFileSync(script, SERVER)
+ connectorId = await connectors.add({ kind: 'stdio', name: 'Databricks', command: process.execPath, args: [script] })
+ await connectors.connect(connectorId)
+ db.saveAgent(agent())
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
+})
+
+afterEach(async () => {
+ await connectors.closeAll()
+ await gateway.stop()
+ db.close()
+ setLang('pt')
+})
+
+describe('a connector tool that fails shows why, in the step and to the agent', () => {
+ it('an error result whose reason is only in structuredContent', async () => {
+ const { step, result } = await ask('structured')
+ expect(step.status).toBe('error')
+ expect(step.error).toContain('Warehouse abc123 is stopped')
+ expect(result.isError).toBe(true)
+ expect(result.text).toContain('Warehouse abc123 is stopped')
+ }, 20_000)
+
+ it('an error result with no text at all says so instead of nothing', async () => {
+ const { step, result } = await ask('empty')
+ expect(step.status).toBe('error')
+ expect(step.error).toMatch(/no message/)
+ expect(result.text).toMatch(/no message/)
+ }, 20_000)
+
+ it('an error result whose text is in an embedded resource', async () => {
+ const { step, result } = await ask('resource')
+ expect(step.error).toContain('TABLE_OR_VIEW_NOT_FOUND: main.sales.orders')
+ expect(result.text).toContain('TABLE_OR_VIEW_NOT_FOUND')
+ }, 20_000)
+
+ it('an MCP error thrown by the server keeps the data it came with', async () => {
+ const { step, result } = await ask('throw')
+ expect(step.status).toBe('error')
+ expect(step.error).toMatch(/^Statement failed \(code -32603\)/)
+ expect(step.error).toContain('User does not have SELECT on main.sales')
+ expect(result.isError).toBe(true)
+ expect(result.text).toContain('PERMISSION_DENIED')
+ }, 20_000)
+
+ it('a call the server never answers says how long it waited', async () => {
+ const { step, result } = await ask('slow')
+ expect(step.status).toBe('error')
+ expect(step.error).toMatch(/didn't answer in 1 s/)
+ expect(result.text).toMatch(/didn't answer in 1 s/)
+ }, 20_000)
+
+ it("a result that doesn't match the tool's own output schema says that, not just 'failed'", async () => {
+ const { step } = await ask('select 1', 'query_typed')
+ expect(step.status).toBe('error')
+ expect(step.error).toMatch(/output schema/)
+ }, 20_000)
+
+ it('a call that works has no error on its step', async () => {
+ const { step, result } = await ask('select id from t')
+ expect(step.status).toBe('done')
+ expect(step.error).toBeUndefined()
+ expect(result.text).toContain('id')
+ }, 20_000)
+})
+
+describe('callError and errorReason', () => {
+ it('turn what a call threw, or an error result, into a reason', () => {
+ expect(callError(new McpError(ErrorCode.RequestTimeout, 'Request timed out'), 120_000)).toMatch(/120 s/)
+ expect(callError(new McpError(-32603, 'Boom', 'stack here'))).toBe('Boom (code -32603): stack here')
+ expect(callError(new Error('fetch failed'))).toBe('fetch failed')
+ expect(errorReason({ content: [{ type: 'text', text: 'bad SQL' }] })).toBe('bad SQL')
+ expect(errorReason({ content: [] })).toMatch(/no message/)
+ })
+})