Build a Custom TypeScript MCP Client
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:
npm install @modelcontextprotocol/clientThe 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
- Fetch the server's tools.
- Provide an allowed subset to the model.
- Validate the model's request.
- Obtain user approval for sensitive actions.
- Execute the tool call with a timeout.
- Validate the result schema.
- Mark the result as untrusted context and provide it to the model.
- 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.
Can you explain it without the notes?
Build a Custom TypeScript MCP Client
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
Client responsibilities
Turn this concept into a clear answer.
Practice this conceptAdapted from 20_MCP_SERVER.md · “10. Build a Custom TypeScript MCP Client”. Examples are study fragments; framework behavior can depend on your version.