AAnvio
Tools & MCP

MCP Bridge

How @anvio/integrations bridges the Model Context Protocol into Anvio's tool-call surface over a real stdio JSON-RPC client.

4 min read

The Model Context Protocol (MCP) is Anvio's mechanism for external tool integration — a registry pattern, not a hardcoded list of vendor SDKs. Per ADR 0006, Anvio uses the standard MCP protocol over stdio to decouple tool integration from any single provider's SDK. Agents call McpToolPort.execute() — they never import an MCP server directly.

Components (@anvio/integrations)

FileResponsibility
integration-registry.tsReads workspace/mcp/servers.yaml, exposes list() / get(id) / listEnabled()
mcp-stdio-client.tsReal MCP client over stdio — spawns the server process, speaks JSON-RPC with Content-Length framing
mcp-bridge.tsMcpBridge — routes listTools()/callTool() to a live stdio client, or a stub if the server isn't configured for stdio
mcp-preset.tsApplies a preset (workspace/mcp/presets/*.yaml.example) into servers.yaml
mcp-first-call-gate.tsPer-session first-use approval tracking for MCP tools
mcp-tool-port.tsThe McpToolPort interface agents call through

IntegrationRegistry

export class IntegrationRegistry {
  async load(): Promise<McpConfig> { /* reads workspace/mcp/servers.yaml */ }
  async list(): Promise<IntegrationEntry[]> { /* all configured servers */ }
  async get(id: string): Promise<IntegrationEntry | null> { /* one server */ }
  async listEnabled(): Promise<IntegrationEntry[]> { /* enabled: true only */ }
}

If servers.yaml doesn't exist yet, load() returns an empty config with firstCallApproval: true — approval-first is the default posture, not opt-in.

McpBridge — real stdio, not just a stub

McpBridge.callTool() (packages/integrations/src/mcp-bridge.ts) tries a real stdio MCP client first, and only falls back to a stub response if the server isn't wired for stdio transport:

async callTool(call: McpToolCall): Promise<McpToolResult> {
  const entry = await this.registry.get(call.serverId);
  if (!entry) return { status: 'failed', error: `MCP server not found: ${call.serverId}`, ... };
  if (!entry.enabled) return { status: 'skipped', error: 'Integration disabled', ... };

  const stdioResult = await this.tryCallStdioTool(entry, call);
  if (stdioResult) return stdioResult;

  // Falls back to a stub only when transport isn't stdio (or ANVIO_MCP_STUB=1)
  return { status: 'completed', transport: 'stub', output: { ok: true, message: `[MCP stub] ...` } };
}

usesStdioTransport() returns true unless entry.server.transport === 'stub' or ANVIO_MCP_STUB=1 is set — so a normally-configured server always attempts the real stdio path.

McpToolResult carries a transport: 'stub' | 'stdio' field explicitly, so callers (and you, debugging) can always tell whether a response came from a live MCP server or the built-in stub:

interface McpToolResult {
  serverId: string;
  toolName: string;
  output: unknown;
  status: 'completed' | 'failed' | 'skipped';
  error?: string;
  transport?: 'stub' | 'stdio';
}

McpStdioClient — the actual protocol implementation

packages/integrations/src/mcp-stdio-client.ts is a minimal but real MCP client: it spawns spec.command with spec.args, resolves ${VAR} placeholders in spec.env against process.env, and speaks JSON-RPC 2.0 framed with Content-Length headers over stdin/stdout — the same wire format the official MCP SDK uses.

async start(): Promise<void> {
  this.proc = spawn(this.spec.command, this.spec.args, { env: resolveEnv(this.spec.env), stdio: ['pipe','pipe','pipe'] });
  await this.request('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'anvio', version: '1.0.0' } });
  this.notify('notifications/initialized', {});
}

async listTools(): Promise<McpStdioToolDescriptor[]> {
  const result = await this.request('tools/list', {});
  return result.tools ?? [];
}

async callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
  const result = await this.request('tools/call', { name, arguments: args });
  // unwraps a single text content block as JSON if possible, else returns raw content
}

Reliability details worth knowing:

  • Auto-restart: ensureRunning() respawns the process up to maxRestarts (default 3) if the previous one exited.
  • Request timeout: every JSON-RPC request rejects after 30 seconds if no response arrives.
  • invalidate(): on any stdio error, the bridge drops the client so the next call spawns a fresh process rather than reusing a broken pipe.
  • stderr passthrough: server stderr is logged with a [mcp-stdio] prefix — see Logging for why this is plain console.error, not a structured logger.

Tool naming

MCP tools are exposed to agents as anvio_mcp__{server}__{tool} (packages/integrations/src/mcp-tool-port.ts naming helpers):

formatMcpToolName('github', 'create_issue')
// => 'anvio_mcp__github__create_issue'

parseMcpToolName('anvio_mcp__github__create_issue')
// => { serverId: 'github', toolName: 'create_issue' }

First-call approval

McpFirstCallGate tracks, per session, which serverId/toolName pairs have already been approved:

class McpFirstCallGate {
  async isApproved(sessionId, serverId, toolName): Promise<boolean> { /* ... */ }
  async approve(sessionId, serverId, toolName): Promise<void> { /* ... */ }
  requiresApproval(): boolean { return this.enabled; }
}

When spec.firstCallApproval: true (the default), each distinct MCP tool needs human approval once per session — after that, the approval is cached both in memory and via an optional persistApproved callback (session metadata), so subsequent calls to the same tool in the same session don't re-prompt.

Health check

anvio mcp list
anvio mcp health

McpBridge.getHealthReport() returns, per configured server: enabled, transport (stdio or stub), connected (is the stdio client's stdin currently writable), restartCount, and toolCount.

Edit on GitHub

Last updated on

On this page