Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Tell the Bot to ask for sign-in when a connector token cannot refresh

Fei2411a90c9ebcf5e6
diff --git a/ds-bot/src/host/connectors/gateway.js b/ds-bot/src/host/connectors/gateway.js
index 6265830b..20667d96 100644
--- a/ds-bot/src/host/connectors/gateway.js
+++ b/ds-bot/src/host/connectors/gateway.js
@@ -72,6 +72,21 @@ export function createGateway({ credential, readOnly, onUnauthorized, log = () =
error: { code: -32600, message: `The ${id} connector is read-only: this tool can change things, so it is off. Turn off the read-only switch in Settings → Connectors to use it.` },
})
+ // A 401 that survives the refresh: answer the JSON-RPC request with a reason
+ // the Bot can act on, instead of an empty HTTP error.
+ const signInAgain = (id, body, upstream, res) => {
+ let rpc
+ try { rpc = JSON.parse(body?.toString('utf8') ?? '') } catch { return false }
+ if (rpc === null || typeof rpc !== 'object' || Array.isArray(rpc) || rpc.id === undefined) return false
+ upstream.resume()
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({
+ jsonrpc: '2.0', id: rpc.id,
+ error: { code: -32001, message: `The ${id} connector needs sign-in again. Call request_connector with id ${id} so the user can sign in, or ask them to sign in under Settings → Connectors.` },
+ }))
+ return true
+ }
+
async function sendUpstream(id, entry, method, path, headers, body) {
return new Promise((resolve, reject) => {
const target = new URL(entry.url)
@@ -87,7 +102,8 @@ export function createGateway({ credential, readOnly, onUnauthorized, log = () =
// This listener must exist before refresh awaits: the response can fail
// before the handler starts consuming it.
upstream.on('error', reject)
- if (upstream.statusCode >= 400) log('ds-bot: connector %s upstream %s HTTP %s (session: %s)', id, method, upstream.statusCode, headers['mcp-session-id'] !== undefined)
+ // GET 405 is the normal answer from servers without a standalone stream.
+ if (upstream.statusCode >= 400 && !(method === 'GET' && upstream.statusCode === 405)) log('ds-bot: connector %s upstream %s HTTP %s (session: %s)', id, method, upstream.statusCode, headers['mcp-session-id'] !== undefined)
resolve(upstream)
})
req.on('error', reject)
@@ -136,6 +152,7 @@ export function createGateway({ credential, readOnly, onUnauthorized, log = () =
upstream = await sendUpstream(id, credential(id) ?? entry, req.method, path, req.headers, body)
}
}
+ if (upstream.statusCode === 401 && signInAgain(id, body, upstream, res)) return
const raw = await readAll(upstream)
const isSse = String(upstream.headers['content-type'] ?? '').includes('text/event-stream')
const payload = isSse ? sseMessage(raw.toString('utf8')) : raw.toString('utf8')
@@ -179,6 +196,7 @@ export function createGateway({ credential, readOnly, onUnauthorized, log = () =
res.end(JSON.stringify({ error: 'connector upstream failed' }))
return
}
+ if (upstream.statusCode === 401 && req.method === 'POST' && signInAgain(id, body, upstream, res)) return
// tools/list without the read-only filter still feeds the annotation cache.
const isList = req.method === 'POST' && body !== undefined && (() => { try { return JSON.parse(body.toString('utf8'))?.method === 'tools/list' } catch { return false } })()
const heads = {}
diff --git a/ds-bot/src/host/connectors/index.js b/ds-bot/src/host/connectors/index.js
index df8ea36d..bf044cec 100644
--- a/ds-bot/src/host/connectors/index.js
+++ b/ds-bot/src/host/connectors/index.js
@@ -529,7 +529,8 @@ export function install(rt) {
const bot = rt.botOf(rt.selfOf(agentId))
if (bot === undefined) return 'Only Bots on the team can use request_connector.'
const connected = id === 'mail' ? mailHasAccounts() : hasCredential(id)
- if (connected && !offFor(id).includes(bot.id)) return `${entry.name} is already connected; use its tools (mcp__${id}__*).`
+ const signIn = statuses.get(id)?.state === 'needs-sign-in'
+ if (connected && !signIn && !offFor(id).includes(bot.id)) return `${entry.name} is already connected; use its tools (mcp__${id}__*).`
if (offFor(id).includes(bot.id)) return `${entry.name} is turned off for you. The user can turn it on in your details.`
if (rt.groupOwners.has(agentId)) return 'Connector cards only work in your own chat. Tell the group you will ask the user in your own chat, and call request_connector there.'
if (!rt.chatOwners.has(agentId)) return 'Connector cards only work in your current own chat.'
diff --git a/ds-bot/test/connectors-engine.test.js b/ds-bot/test/connectors-engine.test.js
index f5863de4..1d10dc82 100644
--- a/ds-bot/test/connectors-engine.test.js
+++ b/ds-bot/test/connectors-engine.test.js
@@ -306,6 +306,9 @@ test('refresh is single-flight, rotates the refresh token, and invalid_grant mea
logs = await rt.diagnostics.entries()
assert.ok(logs.some(row => /connector notion token refresh failed.*dcr/.test(row.text)))
assert.equal(JSON.stringify(logs).includes('RT-2'), false)
+ // A connector that needs sign-in again can still be asked for with a card.
+ const ask = rt.teamTools.find(d => d.name === 'request_connector')
+ assert.doesNotMatch(String(await ask.execute({ id: 'notion', purpose: 'Search pages' }, { agent: { id: 'm1' }, concludeTurn: () => {} })), /already connected/)
})
test('refresh uses the client that signed in: cimd, catalog, and legacy inference', async (t) => {
diff --git a/ds-bot/test/connectors-gateway.test.js b/ds-bot/test/connectors-gateway.test.js
index a9f0aa0b..bb068c51 100644
--- a/ds-bot/test/connectors-gateway.test.js
+++ b/ds-bot/test/connectors-gateway.test.js
@@ -33,6 +33,39 @@ for (const refreshing of [false, true]) {
})
}
+for (const limited of [false, true]) {
+ test(`a 401 that refresh cannot fix answers the call with a sign-in reason${limited ? ' (read-only list)' : ''}`, async (t) => {
+ let hits = 0
+ const upstream = createServer((req, res) => {
+ hits += 1
+ req.resume()
+ req.on('end', () => { res.writeHead(401, { 'www-authenticate': 'Bearer' }); res.end() })
+ })
+ await new Promise(resolve => upstream.listen(0, '127.0.0.1', resolve))
+ t.after(() => upstream.close())
+ let refreshes = 0
+ const gw = createGateway({
+ credential: () => ({ url: `http://127.0.0.1:${upstream.address().port}/mcp`, headers: {} }),
+ readOnly: () => limited,
+ onUnauthorized: async () => { refreshes += 1; return false },
+ })
+ await gw.listen()
+ t.after(() => gw.close())
+ const method = limited ? 'tools/list' : 'tools/call'
+ const response = await fetch(gw.urlFor('notion'), {
+ method: 'POST',
+ headers: { ...gw.headers(), accept: 'application/json, text/event-stream', 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 7, method, params: { name: 'notion-search' } }),
+ })
+ assert.equal(response.status, 200)
+ const answer = await response.json()
+ assert.equal(answer.id, 7)
+ assert.match(answer.error.message, /notion connector needs sign-in again.*request_connector/)
+ assert.equal(refreshes, 1)
+ assert.equal(hits, 1)
+ })
+}
+
test('gateway preserves MCP POST headers and bodies and reports expired sessions without replaying calls', async (t) => {
const seen = []
const upstream = createServer((req, res) => {