Mastodon

Field notes

6 MCP support questions for Factory's Droid, reproduced on the real CLI

Start an MCP server that crashes, and Droid says "Failed to connect to MCP server". The server's own error message isn't on screen, in droid doctor or in Droid's log. I reproduced six support questions about MCP servers with Factory's Droid CLI, and built a checker that says why a server fails.

· 6 cases · Droid 1.21.1 · 28 tests

makes Droid, an AI coding agent that enterprise engineering teams run from the terminal, their editors and their chat tools. Customers connect it to their own tools through MCP servers: an internal API, a database, a ticketing system.

Those servers live on the customer's side, in their files, their network and their credentials, so they generate support questions Factory can't see from its own logs. I took six of them and reproduced each one with the real CLI, Droid 1.21.1. No Factory account was needed: droid mcp and droid doctor --checks mcp run without signing in, and each case used its own throwaway home folder. Here's what the runs settled, and the reply I'd send for each.

Where mcpcheck fits

The customer's side
mcp.json files and servers
User, folder and project configs, and the servers they start or connect to
mcpcheck
Loaded the way Droid loads them
Which files count, which definition wins, then a real MCP handshake with each server
The answer
The real reason
A server's own error, a DNS or proxy failure, an untrusted CA, or the server's 401
What mcpcheck adds to Droid's own checks. Measured with Droid 1.21.1 on 26 November 2026.

1. A server that only says "failed"

The question: a local MCP server shows as failed, and neither droid mcp list nor droid doctor says why.

What the run showed: one lab server crashed on start after printing crash: failed to load its configuration. Droid reported only the generic error. The one failure it explains well is a missing variable:

Case 01, droid mcp list (shortened)
$ droid mcp list
SERVER     STATUS
crash      failed
healthy    connected
needs-env  failed

Issues
crash → Failed to connect to MCP server
needs-env → MCP server credential references an unset environment variable "CASEBOOK_TOKEN"

The crash message wasn't in droid doctor --checks mcp either, or in ~/.factory/logs/droid-log-single.log, although doctor's hint says the log has the full error. mcpcheck runs the configured command and keeps what Droid drops:

Case 01, mcpcheck (shortened)
$ node mcpcheck.mjs --probe
Probe: connecting to each server
[FAIL] crash: the server exited (exit code 1) before finishing the handshake (74 ms)
       Its stderr, which Droid does not show or log:
         crash: failed to load its configuration
[OK]   healthy: connected, 1 tool(s) (68 ms)
[FAIL] needs-env: env.CASEBOOK_TOKEN uses ${CASEBOOK_TOKEN}, which is not set, so Droid won't start it
lib/probe.mjs, lines 103 to 109
child.on('exit', (code, signal) => finish({
  status: 'failed',
  summary: `the server exited (${signal ?? `exit code ${code}`}) before finishing the handshake`,
  details: stderr
    ? ['Its stderr, which Droid does not show or log:', ...tail(stderr).map((l) => `  ${l}`)]
    : ['It wrote nothing to stderr. Run the command yourself to see what happens.'],
}));

The reply, in short: run the exact command from your mcp.json in the terminal you start droid from. Whatever it prints before it exits is the real error.

2. A server stuck on "connecting"

The question: droid mcp list shows a server as "connecting", every time.

What the run showed: the list reports after about 5 seconds, while a local server's default connect timeout is 30. Four lab servers, made to answer slowly:

Server answers afterdroid mcp listdroid doctor --checks mcpmcpcheck --probe
4.5 secondsconnectedconnectedconnected
5 secondsconnectingconnected (5.2 s)connected
8 secondsconnectingconnected (8.2 s)connected
never, connectTimeout 2 sfailed after 2 sfailed after 32 sfailed after 2 s

The list exits with 0 whatever it shows, so a script can't tell "connecting" from "connected". And doctor ignored the 2-second timeout and waited 32 seconds.

The reply, in short: "connecting" means it was still starting when the list printed, often a first npx run. droid doctor --checks mcp waits longer and shows the start time.

3. A remove that refuses, or goes too far

The question: Droid won't remove a server because it's "managed", and removing a broken server made a working one disappear.

What the run showed: Droid rewrites names for display, so "notes/work" and "notes.work" both became "notes-work". Only the later entry, an old crashing copy, ran, and the list showed one row. Removing it deleted both entries from the file. A project server gave the "managed" error:

Case 03 (shortened)
$ droid mcp remove notes-work
Removed MCP server notes-work

$ droid mcp remove team-tools
Error: Cannot remove managed mcp server "team-tools".

"Managed" is the word Factory's docs use for servers an organisation controls. Here it means the server comes from the repo's shared .factory/mcp.json, which the CLI won't edit. The same error blocked removing my own server of the same name from inside the repo.

The reply, in short: edit the repo's file, or disable the server for yourself in /mcp; and keep server names to letters, digits, "_" and "-".

4. A shared config in a parent folder that never loads

The question: a .factory/mcp.json in a folder above several projects never loads. describe this level as an "ancestor directory of the project", for "Servers shared across nested projects under a common parent".

What the run showed: in Droid 1.21.1, nothing above the project root is read. The project root is the git repository's root, or the folder you start droid in when you're not in a repository. So the shared folder's server never loaded, in four runs with and without git:

Started inGit repo?Loaded
workspace/appnothe app's servers, and mine
workspace/app/packages/webnothe package's servers, and mine. The app's are gone
workspace/appyesthe app's servers, and mine
workspace/app/packages/webyesthe package's and the app's servers, and mine. The package's broken copy of shared wins

mcpcheck applies the same rules, and says what it skipped and why:

mcpcheck, run in packages/web (shortened)
Config files Droid loads here, nearest first
  folder   .factory\mcp.json                       2 server(s)
  project  ..\..\.factory\mcp.json                 2 server(s)
  user     ~\.factory\mcp.json                     1 server(s)
Not loaded
  ..\..\..\.factory\mcp.json: it is above the repository root, and Droid 1.21.1 never reads those

Config checks
[WARN] shared: Defined in 2 files, differently. Droid uses the nearest one (the folder-level file) and ignores the rest in this folder.
lib/discover.mjs, lines 57 to 84
export function discover(cwd, home = droidHome()) {
  const start = resolve(cwd);
  const repoRoot = gitRoot(start);
  const projectRoot = repoRoot ?? start;
  const userFile = configIn(resolve(home));
  const loaded = [];
  const ignored = [];

  let aboveRoot = false;
  for (const dir of ancestors(start)) {
    const file = configIn(dir);
    const exists = file !== userFile && existsSync(file);
    if (exists && !aboveRoot) {
      loaded.push({ path: file, level: dir === projectRoot ? 'project' : 'folder' });
    } else if (exists) {
      ignored.push({
        path: file,
        reason: repoRoot
          ? 'it is above the repository root, and Droid 1.21.1 never reads those'
          : 'you are not inside a git repository, so Droid 1.21.1 reads only the .factory folder where you start it',
      });
    }
    if (dir === projectRoot) aboveRoot = true;
  }

  if (existsSync(userFile)) loaded.push({ path: userFile, level: 'user' });
  return { cwd: start, repoRoot, projectRoot, loaded, ignored };
}

The reply, in short: servers you want everywhere belong in your user config, ~/.factory/mcp.json. Either the docs or the behaviour needs to change, and the case ends with a note for Factory's team about it.

5. "Needs authentication" for an API-key server

The question: an internal server uses an API key, and Droid keeps sending people to an OAuth sign-in.

What the run showed: with a wrong key, Droid reads the server's 401 as a sign-in prompt, because OAuth is on by default. The same server with "oauth": false shows the real error:

Case 05, droid mcp list (shortened)
$ CASEBOOK_LAB_KEY=<wrong key> droid mcp list
SERVER          STATUS
keyed           needs authentication
keyed-no-oauth  failed

Issues
keyed → Run droid mcp auth to sign in.
keyed-no-oauth → Failed to connect to MCP server. The server responded with HTTP 401: missing or invalid API key

droid mcp auth does explain it, one step later, then exits with 1. mcpcheck separates the two cases by asking whether the server offers OAuth at all:

lib/probe.mjs, lines 260 to 274
if (response.status === 401) {
  const oauth = config.oauth !== false && await offersOauth(config.url, response, env);
  if (oauth) {
    return { status: 'needs-auth', summary: 'needs an OAuth sign-in (401, and the server offers OAuth)', details: ['Run "droid mcp auth", or /mcp in a session.'], ms: Date.now() - started };
  }
  return {
    status: 'failed',
    summary: `the server refused the request: 401 ${said}`,
    details: config.oauth === false
      ? ['Check the key or token in its headers.']
      : ['It offers no OAuth sign-in, so it most likely wants a key or token in its headers.',
        'Droid shows this as "needs authentication" and suggests "droid mcp auth", which can\'t fix it. Check the key, and set "oauth": false so Droid shows the real error.'],
    ms: Date.now() - started,
  };
}

The reply, in short: set "oauth": false for servers that use a key or token, then check the key.

6. An internal server behind a company proxy and CA

The question: an internal MCP server, reachable through the company proxy with a certificate from the company's own CA, just "fails to connect".

What the run showed: the lab's internal host resolves only through a stand-in proxy, with a certificate from a private CA:

Setupdroid mcp listIn Droid's log
No proxy settingsFailed to connectgetaddrinfo ENOTFOUND
HTTPS_PROXYFailed to connectunable to verify the first certificate
HTTPS_PROXY + NODE_EXTRA_CA_CERTSconnected
HTTPS_PROXY + FACTORY_EXTRA_CA_CERTSconnected
The host in NO_PROXYFailed to connectgetaddrinfo ENOTFOUND

Droid sends MCP traffic through the proxy and honours NO_PROXY, although only mention proxies for model and Factory traffic. FACTORY_EXTRA_CA_CERTS works too: doctor checks it, but the docs don't mention it. mcpcheck named the certificate's issuer, "Casebook Lab Root CA".

The reply, in short: set HTTPS_PROXY and give Droid the company CA with NODE_EXTRA_CA_CERTS. The log entry "Error in MCP server" says which is missing.

How I used AI

I built this with Claude Code and checked it the way I'd check a reply before sending it: every claim comes from a recorded run. The re-runs caught two of my own wrong conclusions before they went in. I first thought droid mcp remove only accepted the rewritten name, but my test had removed the server once already. And I first thought Droid read every parent folder outside git, but my lab folders sat inside a git repository. Rerunning in a clean folder showed the opposite, which became case 4.

The sample

Everything above comes from : mcpcheck, 28 tests, a lab of small MCP servers, a stand-in proxy and a private CA, and a script that reproduces all six cases with the real CLI and rewrites their transcripts. Each case has the reply I'd send and a note for Factory's team.

lib/probe.mjs (307 lines)
lib/probe.mjs
/**
 * Connects to one server the way Droid would and runs the MCP handshake (initialize,
 * then tools/list), without calling any tools. Unlike `droid mcp list`, it says why a
 * connection failed:
 * - for a stdio server, the server's own stderr, which Droid doesn't show or log (cases/01)
 * - it waits as long as the server's connectTimeout (default 30 s for stdio, 10 s for
 *   http), not the ~5 seconds `droid mcp list` waits (cases/02)
 * - for a remote server, the DNS, proxy, certificate or HTTP error behind "Failed to
 *   connect to MCP server" (cases/05 and 06)
 *
 * Returns { status, summary, details: [lines], ms, tools, serverInfo }, where status is
 * connected, failed, needs-auth or timeout.
 */

import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
import { findOnPath } from './validate.mjs';
import { peekCertificate, proxyFor, request } from './netclient.mjs';

const PROTOCOL_VERSION = '2025-06-18';
const CLIENT = { name: 'mcpcheck', version: '1.0.0' };

/** Expands ${NAME} like Droid does; returns { value } or { missing }. */
function expand(value, env) {
  let missing = null;
  const out = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
    if (env[name] === undefined) missing ??= name;
    return env[name] ?? '';
  });
  return missing ? { missing } : { value: out };
}

function expandMap(map = {}, env) {
  const out = {};
  for (const [key, value] of Object.entries(map)) {
    const result = expand(value, env);
    if (result.missing) return { missing: result.missing, key };
    out[key] = result.value;
  }
  return { value: out };
}

const tail = (text, lines = 12) => text.trimEnd().split(/\r?\n/).filter(Boolean).slice(-lines);

/** Quotes a Windows command line for cmd.exe, which .cmd and .bat files need. */
function cmdLine(parts) {
  return parts.map((part) => `"${String(part).replace(/"/g, '""')}"`).join(' ');
}

export function probeStdio(config, { env = process.env, platform = process.platform } = {}) {
  const timeoutMs = config.connectTimeout ?? 30000;
  const extra = expandMap(config.env, env);
  if (extra.missing) {
    return Promise.resolve({
      status: 'failed',
      summary: `env.${extra.key} uses \${${extra.missing}}, which is not set, so Droid won't start it`,
      details: [],
    });
  }

  const resolved = findOnPath(config.command, env, platform);
  if (!resolved) {
    return Promise.resolve({ status: 'failed', summary: `"${config.command}" is not found on PATH`, details: [] });
  }
  const args = config.args ?? [];
  const childEnv = { ...env, ...extra.value };
  const child = platform === 'win32' && /\.(cmd|bat)$/i.test(resolved)
    ? spawn('cmd.exe', ['/d', '/s', '/c', `"${cmdLine([resolved, ...args])}"`], { env: childEnv, windowsVerbatimArguments: true })
    : spawn(resolved, args, { env: childEnv });

  const started = Date.now();
  return new Promise((resolve) => {
    let stderr = '';
    const noise = [];
    let settled = false;
    let serverInfo = null;
    let protocolVersion = null;

    const finish = (result) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      child.kill();
      const details = [...(result.details ?? [])];
      if (noise.length) {
        details.push(`It also wrote ${noise.length} line(s) of plain text to stdout, which should only carry MCP messages (Droid tolerates this): ${JSON.stringify(noise[0].slice(0, 80))}`);
      }
      resolve({ ...result, details, ms: Date.now() - started, serverInfo, protocolVersion });
    };
    const send = (message) => child.stdin.write(`${JSON.stringify(message)}\n`);

    const timer = setTimeout(() => finish({
      status: 'timeout',
      summary: `no answer to initialize within ${timeoutMs / 1000} seconds (its connectTimeout)`,
      details: [
        ...(stderr ? ['Its stderr so far:', ...tail(stderr).map((l) => `  ${l}`)] : []),
      ],
    }), timeoutMs);

    child.stderr.setEncoding('utf8');
    child.stderr.on('data', (chunk) => (stderr += chunk));
    child.on('error', (error) => finish({ status: 'failed', summary: `could not start ${resolved}: ${error.code ?? error.message}`, details: [] }));
    child.on('exit', (code, signal) => finish({
      status: 'failed',
      summary: `the server exited (${signal ?? `exit code ${code}`}) before finishing the handshake`,
      details: stderr
        ? ['Its stderr, which Droid does not show or log:', ...tail(stderr).map((l) => `  ${l}`)]
        : ['It wrote nothing to stderr. Run the command yourself to see what happens.'],
    }));

    createInterface({ input: child.stdout }).on('line', (line) => {
      let message;
      try {
        message = JSON.parse(line);
      } catch {
        if (line.trim()) noise.push(line);
        return;
      }
      if (message.id === 1) {
        if (message.error) {
          finish({ status: 'failed', summary: `initialize returned an error: ${message.error.message}`, details: [] });
          return;
        }
        serverInfo = message.result?.serverInfo ?? null;
        protocolVersion = message.result?.protocolVersion ?? null;
        send({ jsonrpc: '2.0', method: 'notifications/initialized' });
        send({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} });
      } else if (message.id === 2) {
        const tools = message.result?.tools?.length ?? 0;
        finish({ status: 'connected', summary: `connected, ${tools} tool(s)`, tools });
      }
    });

    send({
      jsonrpc: '2.0',
      id: 1,
      method: 'initialize',
      params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT },
    });
  });
}

/** Reads a JSON-RPC reply from a JSON or text/event-stream body. */
function rpcReply(response, id) {
  const type = response.headers['content-type'] ?? '';
  if (/text\/event-stream/.test(type)) {
    for (const line of response.body.split(/\r?\n/)) {
      if (!line.startsWith('data:')) continue;
      try {
        const message = JSON.parse(line.slice(5));
        if (message.id === id) return message;
      } catch { /* keep reading */ }
    }
    return null;
  }
  try {
    return JSON.parse(response.body);
  } catch {
    return null;
  }
}

const TLS_UNTRUSTED = new Set([
  'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'UNABLE_TO_GET_ISSUER_CERT',
  'SELF_SIGNED_CERT_IN_CHAIN', 'DEPTH_ZERO_SELF_SIGNED_CERT',
]);

async function explainNetworkError(error, url, env) {
  const target = new URL(url);
  const where = `${target.hostname}${target.port ? `:${target.port}` : ''}`;
  const proxy = error.proxy ?? proxyFor(url, env);

  if (error.code === 'PROXY_REFUSED') {
    return { summary: `${error.message}`, details: [`Ask for ${where} to be allowed through the proxy, or add it to NO_PROXY if it's reachable directly.`] };
  }
  if (error.viaProxy) {
    return { summary: `could not reach the proxy ${proxy}: ${error.code ?? error.message}`, details: ['Check HTTPS_PROXY.'] };
  }
  if (error.code === 'ENOTFOUND' || error.code === 'EAI_AGAIN') {
    const proxySet = Boolean(env.HTTPS_PROXY ?? env.https_proxy ?? env.HTTP_PROXY ?? env.http_proxy);
    return {
      summary: `${target.hostname} doesn't resolve (${error.code})`,
      details: [proxySet && !proxy
        ? 'A proxy is set, but NO_PROXY matches this host, so the request went direct. If internal names resolve only behind the proxy, take it out of NO_PROXY.'
        : 'No proxy is set. If internal names resolve only behind your company proxy, set HTTPS_PROXY before starting droid. Droid sends MCP traffic through it.'],
    };
  }
  if (error.code === 'ECONNREFUSED') return { summary: `nothing is listening at ${where}`, details: [] };
  if (error.code === 'ETIMEDOUT' || error.code === 'ECONNRESET') return { summary: `${where}: ${error.message}`, details: [] };

  if (TLS_UNTRUSTED.has(error.code)) {
    const cert = await peekCertificate(url, { env });
    return {
      summary: `the certificate isn't trusted on this machine (${error.code})`,
      details: [
        ...(cert ? [`${target.hostname} presents a certificate for "${cert.subject}", issued by "${cert.issuer}".`] : []),
        'Give Droid that issuing CA as a .pem file: set NODE_EXTRA_CA_CERTS (or FACTORY_EXTRA_CA_CERTS) to its path before starting droid.',
      ],
    };
  }
  if (error.code === 'CERT_HAS_EXPIRED') return { summary: `the server's certificate has expired`, details: [] };
  if (error.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
    const cert = await peekCertificate(url, { env });
    return { summary: `the certificate doesn't cover ${target.hostname}`, details: cert ? [`It is for: ${cert.names ?? cert.subject}.`] : [] };
  }
  return { summary: `${error.code ?? 'error'}: ${error.message}`, details: [] };
}

/** Whether the server advertises OAuth: WWW-Authenticate metadata or the discovery documents. */
async function offersOauth(url, response, env) {
  if (/resource_metadata=/i.test(response.headers['www-authenticate'] ?? '')) return true;
  const base = new URL(url);
  for (const path of ['/.well-known/oauth-protected-resource', '/.well-known/oauth-authorization-server']) {
    try {
      const reply = await request(new URL(path, base).href, { env, timeoutMs: 5000 });
      if (reply.status === 200) return true;
    } catch { /* not offered */ }
  }
  return false;
}

export async function probeRemote(config, { env = process.env } = {}) {
  const timeoutMs = config.connectTimeout ?? 10000;
  const headers = expandMap(config.headers, env);
  if (headers.missing) {
    return { status: 'failed', summary: `headers.${headers.key} uses \${${headers.missing}}, which is not set, so Droid won't connect`, details: [] };
  }
  if (config.type === 'sse') {
    try {
      const reply = await request(config.url, { headers: { accept: 'text/event-stream', ...headers.value }, env, timeoutMs, until: () => true });
      return { status: reply.status === 200 ? 'connected' : 'failed', summary: `the legacy SSE endpoint answered ${reply.status} (the full handshake isn't probed for sse)`, details: [] };
    } catch (error) {
      return { status: 'failed', ...(await explainNetworkError(error, config.url, env)) };
    }
  }

  const started = Date.now();
  const post = (message, sessionId) => request(config.url, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      accept: 'application/json, text/event-stream',
      ...(sessionId ? { 'mcp-session-id': sessionId, 'mcp-protocol-version': PROTOCOL_VERSION } : {}),
      ...headers.value,
    },
    body: JSON.stringify(message),
    env,
    timeoutMs,
    until: (text) => text.includes(`"id":${message.id}`),
  });

  let response;
  try {
    response = await post({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT } });
  } catch (error) {
    return { status: 'failed', ...(await explainNetworkError(error, config.url, env)), ms: Date.now() - started };
  }

  const said = response.body.trim().slice(0, 160);
  if (response.status === 401) {
    const oauth = config.oauth !== false && await offersOauth(config.url, response, env);
    if (oauth) {
      return { status: 'needs-auth', summary: 'needs an OAuth sign-in (401, and the server offers OAuth)', details: ['Run "droid mcp auth", or /mcp in a session.'], ms: Date.now() - started };
    }
    return {
      status: 'failed',
      summary: `the server refused the request: 401 ${said}`,
      details: config.oauth === false
        ? ['Check the key or token in its headers.']
        : ['It offers no OAuth sign-in, so it most likely wants a key or token in its headers.',
          'Droid shows this as "needs authentication" and suggests "droid mcp auth", which can\'t fix it. Check the key, and set "oauth": false so Droid shows the real error.'],
      ms: Date.now() - started,
    };
  }
  if (response.status === 404 || response.status === 405) {
    return { status: 'failed', summary: `${response.status} at ${new URL(config.url).pathname}: ${said}`, details: ['Check the URL path. Streamable HTTP servers usually serve MCP at /mcp.'] };
  }
  if (response.status >= 300) {
    return { status: 'failed', summary: `the server answered ${response.status}: ${said}`, details: [] };
  }

  const init = rpcReply(response, 1);
  if (!init?.result) {
    return { status: 'failed', summary: `initialize didn't return a result: ${init?.error?.message ?? said}`, details: [] };
  }
  const sessionId = response.headers['mcp-session-id'];
  let tools = null;
  try {
    await post({ jsonrpc: '2.0', method: 'notifications/initialized' }, sessionId).catch(() => {});
    const list = rpcReply(await post({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }, sessionId), 2);
    tools = list?.result?.tools?.length ?? null;
  } catch { /* tools stay unknown */ }

  return {
    status: 'connected',
    summary: tools === null ? 'connected (tools/list failed)' : `connected, ${tools} tool(s)`,
    details: proxyFor(config.url, env) ? [`Through the proxy ${proxyFor(config.url, env)}.`] : [],
    ms: Date.now() - started,
    tools,
    serverInfo: init.result.serverInfo ?? null,
    protocolVersion: init.result.protocolVersion ?? null,
  };
}

export function probe(config, options) {
  return (config.type ?? 'stdio') === 'stdio' ? probeStdio(config, options) : probeRemote(config, options);
}

To run mcpcheck, you need Node 20 or later and nothing else: node mcpcheck.mjs --probe.

Your turn

Which MCP problem fills your queue?

If you support a coding agent or its MCP servers, I'd like to hear which case you'd add.

Get in touch

More support casebooks: Supabase, Databento and self-hosted Bitwarden. Everything else is on Developer resources.