Part 6 · Inside a Production Coding Agent

MCP Connection, Discovery & Recovery

Confirming the client role; deconstructing OAuth, tool naming, capability discovery, state merging, and reconnection

THE QUESTION THIS PAGE ANSWERS

ANSWER FIRST

What is the key idea behind “MCP Connection, Discovery & Recovery”?

Confirming the client role; deconstructing OAuth, tool naming, capability discovery, state merging, and reconnection

DECISION RULE

Make the claim earn its place. Use this page as a decision aid, not a definition to memorize. Connect the idea to one real task, one observable result, and one failure that would change your mind.

TRY NEXT

Write one question you could answer with evidence after trying this idea.

WATCH FOR

A conclusion that sounds complete but leaves the key assumption untested.

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.

How “MCP: Connection Is Just the Beginning” changes an answer

“A production-grade client also handles config merging, OAuth, capability discovery, namespace isolation, model visibility control, state push, and connection recovery.” shows that a model does not process the “word count” we see. It processes Token pieces. Tokenization affects input length, how much context fits, and how much computation a request consumes.

Length, information, and context are different

As “Determine client vs.” grows, separate three questions: how many Tokens the text becomes, which pieces can change the current decision, and whether older material has fallen outside the context window. Removing repetition is often more useful than simply making the window larger.

  • Draw a state diagram covering config loading, connection, OAuth, capability discovery, registration, search, and invocation
  • Add tool paths for disabled, app-only, and model-visible tools
  • Design two tools with identical names; verify that qualified names resolve the conflict

Keep what can change the decision

Use “The engineering effort in MCP integration concentrates at the protocol periphery.” as an A/B test: keep the same question while removing repeated background, compressing format, and trimming irrelevant history. Compare answer quality, latency, and Token count.

From “MCP: Connection Is Just the Beginning” to “Clarify Protocol Roles”

“MCP: Connection Is Just the Beginning” grounds the problem in “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 responsi…”. “Clarify Protocol Roles” then moves it toward “Determine client vs. server from the call direction, and avoid conflating the internal Hub Server with an MCP Server”. Together, they show that the lesson is not just a conclusion to remember, but a claim with conditions.

Carry the judgment into the next situation

For long text, keep what can change the conclusion before compressing format and history. A larger context is worth its cost only when the added information is useful.

  • “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 responsi…
  • “Clarify Protocol Roles”: Determine client vs. server from the call direction, and avoid conflating the internal Hub Server with an MCP Server
  • “The closing point”: Simulate a stale disconnect event arriving late; explain how the client_id guard protects the new connection

The final “The closing point” brings the discussion to “Simulate a stale disconnect event arriving late; explain how the client_id guard protects the new connection”. The useful thing to carry forward is knowing which judgments must be revisited when input, scale, or risk changes.

Mark as learned Your reading progress updates automatically
← PreviousNext →

Keep reading

The next useful article in the thread.

ARTICLE DISCUSSION

Leave one useful thought here.

Keep the idea that clicked, the question that stayed open, or a small note for the next learner.

Discussing MCP Connection, Discovery & Recovery Inside a Production Coding Agent
3discussionsArticle discussion · synced with the Circle
View in the learning circle
AM
Asha MorganContent editor
INSIGHTField note

I turned one judgment from this article into a small experiment I could run today. Knowing what to observe next is more useful than simply remembering the conclusion.

ARTICLE DISCUSSION7 helpful
LH
Lin HarperIndie developer
INSIGHTInsight

After reading this, I first looked for the conditions behind the idea instead of copying the method into a project. That order made the later trade-offs much clearer.

ARTICLE DISCUSSION5 helpful
KM
Kiki MooreProduct operations
QUESTIONQuestion

When this judgment reaches real work, which constraint should be added first? I am curious which step matters most between reading and the first practical attempt.

ARTICLE DISCUSSION4 helpful