Grok Build Source Course · 12 / 20

MCP: Connection Is Just the Beginning

A production-grade client also handles config merging, OAuth, capability discovery, namespace isolation, model visibility control, state push, and connection recovery. The source code distributes these responsibilities across the MCP crate and Session Actor.

Client Rolestdio / Streamable HTTPOAuthserver__tool50 ms State Coalesce
01 / OBJECTIVES

Learning Objectives

Clarify Protocol Roles

Determine client vs. server from the call direction, and avoid conflating the internal Hub Server with an MCP Server.

Trace Visibility

Explain how tools flow from tools/list into the snapshot, search index, and model registry.

Design a Recovery State Machine

Place OAuth, state coalescing, client identity, and restart back-off within a single connection lifecycle.

02 / CORE VISUAL

From External Server to Model Tool

03 / ROLE CHECK

Client vs. Server: Pinpointing Roles in the Source Code

SOURCE CONFIRMEDGrok Build is an MCP Client

McpClient initiates a stdio or Streamable HTTP connection and performs initialization, list_tools, and call_tool. The Computer Hub MCP Adapter is also described as bridging MCP Server tools into the Hub routing layer.

NOT ESTABLISHEDNo source evidence of a general MCP server role

The Hub Server in xai-grok-workspace belongs to the xAI Computer Hub protocol. The current snapshot contains no entry point exposing Grok Build itself to arbitrary MCP clients via MCP transport, so this lesson confirms only the client role.

04 / OAUTH

OAuth & Where Credentials Actually Live

1 · Reuse or RefreshRead credentials from disk and attempt token refresh first
2 · Browser AuthLaunch user-consent flow when interaction is required
3 · Callback Token ExchangeExchange auth code for access and refresh tokens
4 · Locked WriteFile lock + atomic save for multi-process safety
CONFIG TYPES

Config Fields

oauth_client_id
oauth_client_secret_env_var
oauth_scopes
crates/codegen/xai-grok-config-types/src/mcp.rs
CREDENTIAL STORE

Local JSON File

let path = grok_home
    .join("mcp_credentials.json");
// lock + load + insert + atomic save

The source stores credentials in this file, handling concurrent writes with file locks and atomic saves.

crates/codegen/xai-grok-mcp/src/credentials.rs · oauth.rs
05 / VISIBILITY

How Tools Become Visible to the Model

NAMESPACE

server__tool

The registration name consists of the server name, the reserved separator __, and the original tool name. The source requires exactly one separator occurrence in the full name to avoid parsing ambiguity and ensures that same-named tools from two servers have distinct ToolIds.

crates/codegen/xai-grok-mcp/src/servers.rs: into_registration
TWO AUDIENCES

Model Tools vs. App Tools

Disabled tools are stored in disabled_tool_registrations; only tools where model_visible is true enter the model-side Tool Bridge; tools with ui.resourceUri can be routed to UI notifications independently.

crates/codegen/xai-grok-shell/src/session/acp_session_impl/mcp.rs
SEARCH SNAPSHOT

Large MCP Tool Sets Don't Need to Live in the Prompt Permanently

ToolMetadataSnapshot stores tool and server metadata. The BM25 index supports exact hits by qualified name or bare tool name before returning search results. mcp_initialized signals the search layer when capability discovery is complete.

pub struct ToolMetadataSnapshot {
    pub tools: Vec<ToolMetadata>,
    pub servers: Vec<ServerMetadata>,
    pub mcp_initialized: bool,
}
crates/codegen/xai-grok-shell/src/session/tool_index.rs
06 / RECOVERY

State Coalescing & Restart Protection

InitializingHandshake started
ReadyCapabilities available
NeedsAuthAwaiting authorization
UnavailableConnection lost
DisabledConfig disabled
50 MS COALESCE

Last-Write-Wins Per Key

mcp_dispatcher keys events on (server_name, event_kind) and applies last-write-wins within a 50 ms tumbling window. High-frequency tools/list_changed events ultimately push only a single ACP state update.

IDENTITY GUARD

Stale Disconnects Can't Kill the New Connection

Before removing a dead client, the code compares client_id. If the disconnect event belongs to an already-replaced old client, the current client is preserved and the stale state is discarded.

RESTART POLICY

Different Transports Use Different Recovery Actions

stdio auto-restart uses a fixed back-off of 1s → 4s → 16s and checks guards for shutting down, disabled, and config-removed states. HTTP first attempts in-client recovery with its own back-off. After a successful reconnect, tools are re-discovered and re-registered, then the snapshot is refreshed.

crates/codegen/xai-grok-shell/src/session/mcp_dispatcher.rs · mcp_restart.rs · acp_session_impl/mcp_snapshot.rs
07 / LAB

Lab Exercise: Design a Recoverable Client

30 MIN

Deliverables
State diagram + 6 test cases

  1. Draw a state diagram covering config loading, connection, OAuth, capability discovery, registration, search, and invocation.
  2. Add tool paths for disabled, app-only, and model-visible tools.
  3. Design two tools with identical names; verify that qualified names resolve the conflict.
  4. Simulate 100 tools/list_changed events and write out the expected notification count after 50 ms coalescing.
  5. Simulate a stale disconnect event arriving late; explain how the client_id guard protects the new connection.
  6. Write one recoverable test and one stop-retry condition each for stdio and HTTP.
Takeaway

The engineering effort in MCP integration concentrates at the protocol periphery. Naming, visibility, identity, state coalescing, and recovery strategy together determine whether a connection stays reliably operational over time.

Source Snapshot Note: This page is compiled from the local grok-build-main source code covering MCP, config-types, shell session, and computer-hub adapter. Code excerpts are for educational purposes. Conclusions about the MCP server role are stated conservatively; the internal Hub Server is not treated as evidence of a general-purpose MCP server.