Back to series
· 14 min read

Implementing MCP Server and Client: A Complete Engineering Practice from Capability Registration to Protocol Communication


I. Division of Responsibilities Between MCP Server and Client

The engineering implementation of MCP can be divided into two core parts:

  • MCP Server: Encapsulates external business capabilities as standard MCP interfaces.
  • MCP Client: Connects to the MCP Server, discovers and invokes the capabilities it provides.

The two communicate through the MCP protocol, using the JSON-RPC message format and standard transport mechanisms underneath.

1.1 Core Responsibilities of MCP Server

The MCP Server is the capability provider, responsible for converting business systems into standard capabilities that models can understand and invoke.

Main responsibilities:

Module Responsibility
Capability registration Register Tools, Resources, Prompts
Parameter definition Declare input parameters and data structures
Parameter validation Validate request parameter types and constraints
Request handling Receive and route MCP requests
Business execution Call databases, APIs, file systems, etc.
Result wrapping Convert business results into MCP responses
Access control Verify identity, authorization scope, and operation permissions
Exception handling Handle protocol errors and business errors

The Server does not need to understand the LLM's internal reasoning process. It only needs to provide clear, reliable, and invocable capability interfaces.

1.2 Core Responsibilities of MCP Client

The MCP Client is the capability caller, usually running inside the Host.

Main responsibilities:

Module Responsibility
Connection management Establish and close Server connections
Transport management Manage STDIO or Streamable HTTP
Protocol handling Send and parse JSON-RPC messages
Capability discovery Retrieve tools, resources, and prompts provided by the Server
Tool invocation Initiate calls based on tool names and parameters
Request management Manage request IDs, timeouts, and concurrency
Result handling Parse the content returned by tools
Exception handling Handle connection failures, protocol errors, and business errors

The Client does not directly execute the Server's internal business logic; instead, it requests the Server to perform operations through the protocol.

1.3 Complete Collaboration Between the Two

flowchart TB
    A["User request"] --> B["Host"]
    B --> C["LLM"]
    B --> D["MCP Client"]

    D --> E["Establish transport connection"]
    E --> F["MCP Server"]
    F --> G["Capability registry"]
    F --> H["Business processing layer"]
    H --> I["Database / API / File System"]

    D --> J["Discover Tools"]
    J --> G
    D --> K["Invoke Tool"]
    K --> F
    F --> H
    H --> L["Return execution result"]
    L --> D
    D --> B
    B --> C

    style A fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style B fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style C fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#EAF3EC,stroke:#83A995,color:#315D49
    style I fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style L fill:#DCEFE5,stroke:#4F8B70,color:#24563F

Two levels need to be distinguished here:

Protocol invocation and model decision-making are not the same thing.

The MCP Client can directly invoke tools, and it does not require every invocation to go through the LLM. The model decides when to use tools, the Host coordinates the model and MCP Client, and the Client executes protocol invocations.


II. Internal Architecture of MCP Server

A maintainable MCP Server should not be merely a collection of several tool handler functions; it should have a clear layered structure.

2.1 Recommended Architecture

flowchart TB
    A["MCP Client"] --> B["Transport Layer"]
    B --> C["Protocol Handler"]
    C --> D["Method Router"]

    D --> E["Tools Registry"]
    D --> F["Resources Registry"]
    D --> G["Prompts Registry"]

    E --> H["Tool Handler"]
    F --> I["Resource Handler"]
    G --> J["Prompt Handler"]

    H --> K["Application Service"]
    I --> K
    J --> K

    K --> L["Repository / Adapter"]
    L --> M["Database / External API / File System"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style D fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
    style E fill:#EAF3EC,stroke:#83A995,color:#315D49
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#EAF3EC,stroke:#83A995,color:#315D49
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style K fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style L fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style M fill:#F5F8F4,stroke:#B5CBBB,color:#40594A

Responsibilities of each layer:

  • Transport Layer: handles STDIO or HTTP message transport.
  • Protocol Handler: parses JSON-RPC messages and handles protocol semantics.
  • Method Router: dispatches requests based on the MCP method.
  • Registry: maintains registered tools, resources, and prompts.
  • Handler: executes the processing logic for the corresponding capability.
  • Application Service: implements business rules.
  • Repository / Adapter: accesses underlying systems.

SDKs usually already encapsulate transport, protocol parsing, and method routing, so developers mainly implement capability registration, business processing, and security controls.

2.2 Core Objects of the Server

Taking TypeScript SDK v2 as an example, the server uses McpServer to create a protocol service instance.

Core concepts:

Object Purpose
McpServer Manages server capabilities and protocol interfaces
Tool Registers executable tools
Resource Registers readable resources
Prompt Registers prompt templates
Transport Provides the underlying communication channel
Handler Actually handles business requests

The server's lifecycle is started and shut down by the application, while transport objects carry protocol messages.

2.3 Creating a Project

The current TypeScript SDK v2 uses separate Server and Client packages.

mkdir mcp-demo
cd mcp-demo

npm init -y

npm install @modelcontextprotocol/server zod
npm install -D typescript tsx @types/node

npx tsc --init

Recommended project structure:

mcp-demo/
├── src/
│   ├── server/
│   │   ├── index.ts
│   │   ├── tools.ts
│   │   ├── resources.ts
│   │   └── prompts.ts
│   ├── services/
│   │   └── user-service.ts
│   ├── repositories/
│   │   └── user-repository.ts
│   └── shared/
│       └── types.ts
├── package.json
└── tsconfig.json

Here, the MCP protocol layer and the business service layer are separated to avoid tool handler functions directly taking on all business logic.


3. MCP Server: Implementing Tool Registration and Invocation

Tools are the most common capability type of an MCP Server.

They allow the Client to discover a tool's name, description, and input structure, and to request execution via tools/call.

3.1 Defining a Tool

Take a user query tool as an example.

import * as z from "zod/v4";

const inputSchema = {
  userId: z.string().min(1).describe("用户 ID"),
};

async function getUser(userId: string) {
  return {
    id: userId,
    name: "Alice",
    email: "alice@example.com",
  };
}

A tool needs three core elements:

  1. Name: used to locate the tool when calling it.
  2. Description: helps the model and client understand the tool's purpose.
  3. Input Schema: defines the structure and constraints of the invocation parameters.

A tool description should not be just a name. For the model, description quality directly affects tool selection and the accuracy of parameter construction.

3.2 Registering a Tool

import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";

const server = new McpServer({
  name: "user-service",
  version: "1.0.0",
});

server.registerTool(
  "get_user",
  {
    title: "查询用户",
    description: "根据用户 ID 查询用户基本信息",
    inputSchema: {
      userId: z.string().min(1),
    },
  },
  async ({ userId }) => {
    const user = await getUser(userId);

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(user),
        },
      ],
    };
  },
);

registerTool binds the tool metadata, input Schema, and execution handler together.

When the Client calls tools/list, the SDK can generate the tool description from the registration information.

When the Client calls tools/call, the SDK locates the corresponding handler by tool name.

3.3 Tool Parameter Validation

Parameter validation is a very important part of a Server implementation.

You must not assume that all requests are valid just because the Client declares a parameter Schema.

Reasons include:

  • The Client may have implementation defects.
  • Parameters may be generated by the model.
  • Users may construct malicious requests.
  • Older versions of the Client may send incompatible parameters.
  • Network requests may be modified by humans.

For example:

const searchSchema = {
  keyword: z.string().min(1).max(100),
  limit: z.number().int().min(1).max(50).default(10),
};

This includes:

  • Type constraints.
  • Non-empty constraints.
  • Character length limits.
  • Integer constraints.
  • Numeric range limits.
  • Default values.

A parameter Schema is both a protocol interface description and an important basis for server-side input validation.

However, Schema validation cannot replace business permission checks. For example, even if userId is a valid string, it does not mean the current user has permission to read that user's data.

3.4 Tool Return Results

MCP tools typically return content via content.

For example:

return {
  content: [
    {
      type: "text",
      text: "查询成功",
    },
  ],
};

You can also return structured data:

return {
  content: [
    {
      type: "text",
      text: "查询成功",
    },
  ],
  structuredContent: {
    id: "1001",
    name: "Alice",
    active: true,
  },
};

The two serve different purposes:

  • content: for general-purpose content display and processing.
  • structuredContent: provides structured results for direct consumption by client programs.

If a tool defines an output Schema, ensure that the actual returned data conforms to that structure.

Do not simply JSON-serialize all results into text. For data that needs programmatic processing, structured output is more appropriate.

3.5 Complete Server Example

Below is an implementation of a user service MCP Server that can be started via STDIO.

// src/server/index.ts

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

const users = [
  {
    id: "1001",
    name: "Alice",
    email: "alice@example.com",
  },
  {
    id: "1002",
    name: "Bob",
    email: "bob@example.com",
  },
];

const server = new McpServer({
  name: "user-service",
  version: "1.0.0",
});

// Register the user lookup tool
server.registerTool(
  "get_user",
  {
    title: "Get user",
    description: "Look up user information by user ID",
    inputSchema: {
      userId: z.string().min(1),
    },
  },
  async ({ userId }) => {
    const user = users.find((item) => item.id === userId);

    if (!user) {
      return {
        content: [
          {
            type: "text",
            text: `User not found: ${userId}`,
          },
        ],
        isError: true,
      };
    }

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(user),
        },
      ],
      structuredContent: user,
    };
  },
);

// Register the user list tool
server.registerTool(
  "list_users",
  {
    title: "User list",
    description: "Query the list of users in the system",
    inputSchema: {
      keyword: z.string().optional(),
    },
  },
  async ({ keyword }) => {
    const result = users.filter((user) => {
      if (!keyword) return true;

      return (
        user.name.includes(keyword) ||
        user.email.includes(keyword)
      );
    });

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(result),
        },
      ],
      structuredContent: {
        users: result,
        total: result.length,
      },
    };
  },
);

// Start the STDIO server
serveStdio(() => server);

Start it:

npx tsx src/server/index.ts

This server communicates with the MCP client over standard input and standard output.

Note: in a real STDIO server, stdout may only be used for MCP protocol messages. Debug logs should be written to stderr; do not pollute the protocol channel with ordinary console.log.


4. MCP Server: Implementing Resources and Prompts

Besides Tools, a server can also provide Resources and Prompts.

The three have different design goals and cannot simply be handled as if they were all the same kind of tool.

4.1 Resources: Providing Data Resources

Resources are mainly used to expose readable data.

For example:

  • Configuration files.
  • Project documentation.
  • Read-only information from a database.
  • Data returned by an API.
  • System runtime status.

Register a resource:

server.registerResource(
  "project-config",
  "config://project",
  {
    title: "项目配置",
    description: "读取当前项目的配置文件",
    mimeType: "application/json",
  },
  async (uri) => {
    const config = {
      name: "mcp-demo",
      version: "1.0.0",
      environment: "development",
    };

    return {
      contents: [
        {
          uri: uri.href,
          mimeType: "application/json",
          text: JSON.stringify(config),
        },
      ],
    };
  },
);

The key to a Resource is the URI.

The Client can read a specified resource by URI without needing to know the database or file system implementation behind the resource.

4.2 Resource Template: Parameterized Resources

Some resources are not fixed addresses but are dynamically located based on parameters.

For example:

user://1001
user://1002
user://1003

Resource Template can be used in such scenarios.

server.registerResource(
  "user-profile",
  "user://{userId}",
  {
    title: "用户资料",
    description: "根据用户 ID 读取用户资料",
    mimeType: "application/json",
  },
  async (uri, { userId }) => {
    const user = users.find(
      (item) => item.id === userId,
    );

    if (!user) {
      throw new Error("User not found");
    }

    return {
      contents: [
        {
          uri: uri.href,
          mimeType: "application/json",
          text: JSON.stringify(user),
        },
      ],
    };
  },
);

Resource Template is suitable for parameterized resource access, but it is still a resource-reading mechanism and is not equivalent to an executable Tool.

4.3 Prompts: Providing Reusable Prompt Templates

Prompts are used to expose reusable prompt templates to the Client.

For example, a code review template:

server.registerPrompt(
  "review_code",
  {
    title: "代码审查",
    description: "根据指定语言审查代码",
    argsSchema: {
      language: z.string(),
      code: z.string(),
    },
  },
  async ({ language, code }) => {
    return {
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: `
请审查以下 ${language} 代码。

重点检查:
1. 逻辑错误
2. 性能问题
3. 安全风险
4. 可维护性

代码:

${code}
`,
          },
        },
      ],
    };
  },
);

The focus of Prompts is prompt template management, not executing external business operations.

4.4 Choosing Among the Three Capabilities

Capability Primary Use Executes Operations?
Tools Execute business actions or calculations Yes
Resources Expose readable data Primarily for reading
Prompts Provide reusable prompt templates Not responsible for business execution

When choosing, follow these guidelines:

  • If you need to execute queries, create, modify, or calculate, prioritize Tool.
  • If you need to provide readable data, consider Resource.
  • If you need to provide standardized prompt templates, consider Prompt.

In practice, the three can be used in combination.


5. MCP Server: Business Logic and Exception Handling

Tool registration is only the entry point; the real engineering challenge lies in reliable execution of business logic.

5.1 Do Not Put Business Logic in the Tool Handler

Not recommended:

server.registerTool(
  "create_order",
  {
    description: "创建订单",
    inputSchema: {
      productId: z.string(),
      quantity: z.number(),
    },
  },
  async ({ productId, quantity }) => {
    // Parameter validation
    // User permission check
    // Inventory query
    // Price calculation
    // Database transaction
    // Order creation
    // Logging
    // Return result
  },
);

This approach tightly couples protocol handling and business logic.

A more reasonable approach is to layer it:

server.registerTool(
  "create_order",
  {
    description: "创建订单",
    inputSchema: {
      productId: z.string(),
      quantity: z.number().int().min(1),
    },
  },
  async ({ productId, quantity }) => {
    const result = await orderService.createOrder({
      productId,
      quantity,
    });

    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(result),
        },
      ],
      structuredContent: result,
    };
  },
);

Business rules go in orderService, and data access goes in the Repository.

This way, the same set of business logic can be reused by the MCP Server, REST API, and background tasks.

5.2 Business Errors and Protocol Errors

An MCP Server needs to distinguish between two types of failures.

Protocol errors:

  • Invalid JSON-RPC format.
  • Method does not exist.
  • Invalid parameter structure.
  • The request does not meet protocol requirements.

These errors are handled by the SDK's protocol layer.

Tool execution errors:

  • User does not exist.
  • Insufficient inventory.
  • Database unavailable.
  • External API request failed.
  • The current user does not have permission to execute this operation.

Tool business errors can be expressed through the tool result's isError.

For example:

server.registerTool(
  "get_user",
  {
    description: "查询用户",
    inputSchema: {
      userId: z.string(),
    },
  },
  async ({ userId }) => {
    try {
      const user = await userService.getUser(userId);

      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(user),
          },
        ],
        structuredContent: user,
      };
    } catch (error) {
      console.error("get_user failed:", error);

      return {
        content: [
          {
            type: "text",
            text: "查询用户失败,请检查用户 ID 或稍后重试",
          },
        ],
        isError: true,
      };
    }
  },
);

In production, database connection strings, SQL stack traces, internal file paths, or access tokens should not be returned directly to the model.

5.3 Idempotency and Side-Effect Control

For read-only tools, repeated calls usually do not modify data.

However, for the following operations:

  • Creating orders.
  • Deducting inventory.
  • Transferring funds.
  • Deleting files.
  • Modifying user permissions.

Repeated execution may have serious consequences.

Therefore, tools with side effects should consider:

  1. Idempotency keys.
  2. Operation records.
  3. Database transactions.
  4. State validation.
  5. Duplicate request detection.
  6. User confirmation for high-risk operations.

An MCP request ID is only a protocol-layer request correlation identifier and cannot be used directly as a business idempotency key.

The same business action may be retried with different request IDs, so a separate business idempotency mechanism needs to be designed.


6. MCP Server: STDIO and Streamable HTTP Implementation

The Server's business capabilities can remain consistent, while the transport layer is chosen based on the deployment scenario.

6.1 STDIO Server

STDIO is suitable for local tool integration.

For example:

  • Local file systems.
  • Local code repositories.
  • Development environment tools.
  • Desktop AI applications.

Using the official TypeScript SDK v2:

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";

const server = new McpServer({
  name: "local-tools",
  version: "1.0.0",
});

server.registerTool(
  "hello",
  {
    description: "返回问候信息",
    inputSchema: {},
  },
  async () => ({
    content: [
      {
        type: "text",
        text: "Hello MCP",
      },
    ],
  }),
);

serveStdio(() => server);

After the Host starts the Server subprocess, the Client communicates with it through the subprocess's standard input and output.

6.2 Streamable HTTP Server

Remote deployments typically use Streamable HTTP.

import { McpServer } from "@modelcontextprotocol/server";
import { serve } from "@modelcontextprotocol/server/http";

const server = new McpServer({
  name: "remote-tools",
  version: "1.0.0",
});

server.registerTool(
  "get_status",
  {
    description: "获取系统运行状态",
    inputSchema: {},
  },
  async () => ({
    content: [
      {
        type: "text",
        text: JSON.stringify({
          status: "healthy",
          timestamp: new Date().toISOString(),
        }),
      },
    ],
  }),
);

serve(server, {
  port: 3000,
});

This shows the HTTP startup mode of SDK v2. In actual deployment, authentication, listen address, request limits, and shutdown procedures also need to be configured according to the SDK version and runtime environment in use.

6.3 How to Choose a Transport Layer

Scenario Recommended Transport
Local desktop application STDIO
Local development tools STDIO
Local subprocess integration STDIO
Remote enterprise service Streamable HTTP
Multi-instance deployment Streamable HTTP
Cloud MCP service Streamable HTTP

Business capabilities should not be coupled to transport implementations.

The same Server can expose the same business interface through different Transports, but the corresponding transport adapter should be configured according to the specific SDK interface and deployment method.


VII. Internal Architecture of the MCP Client

The MCP Client is responsible for connecting to the Server and using the capabilities it provides.

It typically includes the following modules:

Module Responsibility
Client Instance MCP client instance
Transport Transport connection
Protocol Layer JSON-RPC message management
Discovery Capability discovery
Tool Manager Tool listing and invocation
Resource Manager Resource listing and reading
Prompt Manager Prompt template listing and retrieval
Request Manager Request correlation, timeout, and concurrency
Result Adapter Result transformation

7.1 Client Workflow

flowchart TD
    A["Create MCP Client"] --> B["Create Transport"]
    B --> C["Connect to MCP Server"]
    C --> D["Determine protocol version"]
    D --> E["Discover Server capabilities"]
    E --> F["Get Tools / Resources / Prompts"]
    F --> G["Save available capabilities"]
    G --> H["Wait for invocation requests"]
    H --> I["Construct MCP request"]
    I --> J["Send request"]
    J --> K["Receive response"]
    K --> L["Parse execution result"]
    L --> M["Return to Host"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#EAF3EC,stroke:#83A995,color:#315D49
    style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style H fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#EAF3EC,stroke:#83A995,color:#315D49
    style K fill:#EAF3EC,stroke:#83A995,color:#315D49
    style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style M fill:#DCEFE5,stroke:#4F8B70,color:#24563F

Note: The exact order of capability discovery and connection establishment depends on the protocol version and SDK. Older protocol versions require an initialization handshake to be completed first; newer stateless protocols can perform capability discovery when needed and then send independent requests.

7.2 Creating a Client

TypeScript SDK v2 splits the Client and Server into separate packages.

Install:

npm install @modelcontextprotocol/client

Create a client:

import { Client } from "@modelcontextprotocol/client";

const client = new Client({
  name: "demo-client",
  version: "1.0.0",
});

The Client is responsible for capability invocation at the MCP protocol layer, not for deciding whether a large model should use a particular tool.

7.3 Connecting to a STDIO Server

The Client can start a local MCP Server child process.

import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";

const client = new Client({
  name: "demo-client",
  version: "1.0.0",
});

const transport = new StdioClientTransport({
  command: "npx",
  args: ["tsx", "src/server/index.ts"],
});

await client.connect(transport);

Here, the Transport is responsible for:

  • Starting the Server process.
  • Managing standard input and output.
  • Sending JSON-RPC messages.
  • Receiving messages returned by the Server.
  • Handling connection termination.

The Client does not need to implement JSON-RPC encoding and decoding itself.

7.4 Discovering the Tool List

After a successful connection, you can retrieve the tools provided by the Server.

const result = await client.listTools();

console.log(result.tools);

A typical return structure:

```json { "tools": [ { "name": "get_user", "description": "Query user information by user ID", "inputSchema": { "type": "object", "properties": { "userId": { "type": "string" } }, "required": ["userId"] } } ] } ```

The Client can build a tool registry from the tool list, for use by the Host or the model.

7.5 Calling a Tool

const result = await client.callTool({
  name: "get_user",
  arguments: {
    userId: "1001",
  },
});

console.log(result);

The Client does not need to know how the tool accesses the database internally, nor does it need to know the specific address of the business API.

It only needs to know the tool name, the parameter structure, and the call result.

7.6 Reading a Resource

const result = await client.readResource({
  uri: "config://project",
});

console.log(result.contents);

7.7 Getting a Prompt

const result = await client.getPrompt({
  name: "review_code",
  arguments: {
    language: "TypeScript",
    code: "const a = 1;",
  },
});

console.log(result.messages);

What is shown above is the SDK's high-level calling interface. Constructor parameters, import paths, and transport adaptation APIs may differ across SDK versions, so actual projects should follow the API documentation for the locked version.


8. MCP Client: Tool Discovery and Dynamic Invocation

One of the Client's important capabilities is dynamically discovering the tools provided by Servers.

This means the Host does not have to hard-code all tool names and parameters in the code.

8.1 Dynamic Tool Registration

Suppose the Client is connected to three Servers:

  • GitHub Server.
  • Database Server.
  • Filesystem Server.

They each provide different tools.

The Client can discover the tools in a unified way and build a tool registry.

flowchart TD
    A["MCP Client Manager"] --> B["GitHub Client"]
    A --> C["Database Client"]
    A --> D["Filesystem Client"]

    B --> E["GitHub Tools"]
    C --> F["Database Tools"]
    D --> G["Filesystem Tools"]

    E --> H["Unified Tool Registry"]
    F --> H
    G --> H

    H --> I["Host / LLM Tool Adapter"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#EAF3EC,stroke:#83A995,color:#315D49
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#EAF3EC,stroke:#83A995,color:#315D49
    style H fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style I fill:#DCEFE5,stroke:#4F8B70,color:#24563F

8.2 Tool Name Conflicts

Different Servers may register tools with the same name.

For example:

github.search
database.search
filesystem.search

If only search is used as the global name, a conflict may arise.

Namespacing is recommended:

const toolRegistry = {
  "github.search": {
    server: "github",
    tool: "search",
  },
  "database.search": {
    server: "database",
    tool: "search",
  },
  "filesystem.search": {
    server: "filesystem",
    tool: "search",
  },
};

Namespaces not only resolve naming conflicts; they also help the Host identify a tool's source and permission scope.

8.3 Dynamic Changes to the Tool List

A Server's tool set may change.

For example:

  • An administrator enables a new business capability.
  • A plugin adds tools after an upgrade.
  • User permissions change.
  • The Server dynamically registers tools based on configuration.

The Client should not permanently assume that the tool list discovered the first time is the final list.

It can re-fetch the tool list based on list-change notifications provided by the Server, connection status, and application policy.

It should also handle:

  • A tool being deleted.
  • Changes to a tool's parameter structure.
  • Changes to a tool's name.
  • Permission changes.
  • The Server being unavailable.

Tool descriptions and parameter schemas also need to be included in cache version management to prevent the Client from invoking tools using stale definitions.


9. MCP Client: Multi-Server Connection Management

Real AI applications usually need to connect to multiple MCP Servers.

Therefore, you cannot just implement a simple Client instance; you also need to build a Client Manager.

9.1 Multi-Server Architecture

flowchart TB
    A["Host"] --> B["MCP Client Manager"]

    B --> C["Client A"]
    B --> D["Client B"]
    B --> E["Client C"]

    C --> F["GitHub Server"]
    D --> G["Database Server"]
    E --> H["Filesystem Server"]

    F --> I["GitHub API"]
    G --> J["Database"]
    H --> K["File System"]

    style A fill:#DCEFE5,stroke:#4F8B70,color:#24563F
    style B fill:#EAE8FA,stroke:#A49BD5,color:#51477D
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#EAF3EC,stroke:#83A995,color:#315D49
    style G fill:#EAF3EC,stroke:#83A995,color:#315D49
    style H fill:#EAF3EC,stroke:#83A995,color:#315D49
    style I fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style J fill:#F5F8F4,stroke:#B5CBBB,color:#40594A
    style K fill:#F5F8F4,stroke:#B5CBBB,color:#40594A

One Client usually corresponds to the logical connection to one Server.

The Host manages multiple connections through the Client Manager, rather than mixing the communication logic of multiple Servers into one Client.

9.2 Implementation Approach for the Client Manager