Intermediate·Concept·2 min read

Build a Custom TypeScript MCP Client

Practice this question

Client responsibilities

  • Connect the transport.
  • Initialize and negotiate capabilities.
  • Discover tools, resources, and prompts.
  • Orchestrate tool calls.
  • Validate results and present them safely.
  • Handle cancellation, timeouts, and cleanup.

Install the stable v2 client package:

Shell
npm install @modelcontextprotocol/client

The high-level client exposes helpers such as listing tools and calling a tool. Choose the exact transport constructor from the current SDK documentation because local stdio and remote HTTP setups differ.

Safe orchestration loop

  1. Fetch the server's tools.
  2. Provide an allowed subset to the model.
  3. Validate the model's request.
  4. Obtain user approval for sensitive actions.
  5. Execute the tool call with a timeout.
  6. Validate the result schema.
  7. Mark the result as untrusted context and provide it to the model.
  8. Enforce a maximum number of steps.

Infinite-loop prevention

  • Set a maximum number of tool calls per turn.
  • Detect repeated identical calls.
  • Enforce an overall deadline and token budget.
  • Define explicit terminal states.
  • Retry only transient, idempotent operations.
Adapted from 20_MCP_SERVER.md · “10. Build a Custom TypeScript MCP Client”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.