> ## Documentation Index
> Fetch the complete documentation index at: https://model-context-protocol.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 核心架构

> 了解 MCP 如何连接客户端、服务器和 LLM

模型上下文协议（MCP）建立在一个灵活、可扩展的架构之上，使 LLM 应用程序和集成之间的通信无缝进行。本文档涵盖了核心架构组件和概念。

## 概述

MCP 遵循客户端-服务器架构，其中：

* **主机**是 LLM 应用程序（如 Claude 桌面版或 IDE），它们发起连接
* **客户端**在主机应用程序内维护与服务器的 1:1 连接
* **服务器**向客户端提供上下文、工具和提示

```mermaid theme={null}
flowchart LR
    subgraph "&nbsp;主机（例如，Claude 桌面版）&nbsp;"
        client1[MCP 客户端]
        client2[MCP 客户端]
    end
    subgraph "服务器进程"
        server1[MCP 服务器]
    end
    subgraph "服务器进程"
        server2[MCP 服务器]
    end

    client1 <-->|传输层| server1
    client2 <-->|传输层| server2
```

## 核心组件

### 协议层

协议层处理消息框架、请求/响应链接和高级通信模式。

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    class Protocol<Request, Notification, Result> {
        // 处理传入请求
        setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void

        // 处理传入通知
        setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void

        // 发送请求并等待响应
        request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>

        // 发送单向通知
        notification(notification: Notification): Promise<void>
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    class Session(BaseSession[RequestT, NotificationT, ResultT]):
        async def send_request(
            self,
            request: RequestT,
            result_type: type[Result]
        ) -> Result:
            """
            发送请求并等待响应。如果响应包含错误，则引发 McpError。
            """
            # 请求处理实现

        async def send_notification(
            self,
            notification: NotificationT
        ) -> None:
            """发送不期望响应的单向通知。"""
            # 通知处理实现

        async def _received_request(
            self,
            responder: RequestResponder[ReceiveRequestT, ResultT]
        ) -> None:
            """处理来自另一方的传入请求。"""
            # 请求处理实现

        async def _received_notification(
            self,
            notification: ReceiveNotificationT
        ) -> None:
            """处理来自另一方的传入通知。"""
            # 通知处理实现
    ```
  </Tab>
</Tabs>

关键类包括：

* `Protocol`
* `Client`
* `Server`

### 传输层

传输层处理客户端和服务器之间的实际通信。MCP 支持多种传输机制：

1. **Stdio 传输**
   * 使用标准输入/输出进行通信
   * 适用于本地进程

2. **HTTP 和 SSE 传输**
   * 使用服务器发送事件进行服务器到客户端消息传递
   * 使用 HTTP POST 进行客户端到服务器消息传递

所有传输都使用 [JSON-RPC](https://www.jsonrpc.org/) 2.0 交换消息。有关模型上下文协议消息格式的详细信息，请参阅[规范](https://model-context-protocol.github.io)。

### 消息类型

MCP 具有以下主要类型的消息：

1. **请求**期望来自另一方的响应：
   ```typescript theme={null}
   interface Request {
     method: string;
     params?: { ... };
   }
   ```

2. **结果**是对请求的成功响应：
   ```typescript theme={null}
   interface Result {
     [key: string]: unknown;
   }
   ```

3. **错误**表示请求失败：
   ```typescript theme={null}
   interface Error {
     code: number;
     message: string;
     data?: unknown;
   }
   ```

4. **通知**是单向消息，不期望响应：
   ```typescript theme={null}
   interface Notification {
     method: string;
     params?: { ... };
   }
   ```

## 连接生命周期

### 1. 初始化

```mermaid theme={null}
sequenceDiagram
    participant Client
    participant Server

    Client->>Server: 初始化请求
    Server->>Client: 初始化响应
    Client->>Server: 已初始化通知

    Note over Client,Server: 连接准备就绪
```

1. 客户端发送 `initialize` 请求，包含协议版本和功能
2. 服务器响应其协议版本和功能
3. 客户端发送 `initialized` 通知作为确认
4. 正常消息交换开始

### 2. 消息交换

初始化后，支持以下模式：

* **请求-响应**：客户端或服务器发送请求，另一方响应
* **通知**：任一方发送单向消息

### 3. 终止

任一方可以终止连接：

* 通过 `close()` 进行干净关闭
* 传输断开
* 错误情况

## 错误处理

MCP 定义了以下标准错误代码：

```typescript theme={null}
enum ErrorCode {
  // 标准 JSON-RPC 错误代码
  ParseError = -32700,
  InvalidRequest = -32600,
  MethodNotFound = -32601,
  InvalidParams = -32602,
  InternalError = -32603
}
```

SDK 和应用程序可以定义其自己的错误代码，代码大于 -32000。

错误通过以下方式传播：

* 对请求的错误响应
* 传输上的错误事件
* 协议级错误处理程序

## 实现示例

以下是实现 MCP 服务器的基本示例：

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { Server } from "@modelcontextprotocol/sdk/server/index.js";
    import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

    const server = new Server({
      name: "example-server",
      version: "1.0.0"
    }, {
      capabilities: {
        resources: {}
      }
    });

    // 处理请求
    server.setRequestHandler(ListResourcesRequestSchema, async () => {
      return {
        resources: [
          {
            uri: "example://resource",
            name: "Example Resource"
          }
        ]
      };
    });

    // 连接传输
    const transport = new StdioServerTransport();
    await server.connect(transport);
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import asyncio
    import mcp.types as types
    from mcp.server import Server
    from mcp.server.stdio import stdio_server

    app = Server("example-server")

    @app.list_resources()
    async def list_resources() -> list[types.Resource]:
        return [
            types.Resource(
                uri="example://resource",
                name="Example Resource"
            )
        ]

    async def main():
        async with stdio_server() as streams:
            await app.run(
                streams[0],
                streams[1],
                app.create_initialization_options()
            )

    if __name__ == "__main__":
        asyncio.run(main)
    ```
  </Tab>
</Tabs>

## 最佳实践

### 传输选择

1. **本地通信**
   * 对于本地进程，使用 stdio 传输
   * 适用于同一台机器的通信
   * 简单的进程管理

2. **远程通信**
   * 对于需要 HTTP 兼容性的场景，使用 SSE
   * 考虑包括身份验证和授权在内的安全隐患

### 消息处理

1. **请求处理**
   * 彻底验证输入
   * 使用类型安全的架构
   * 优雅地处理错误
   * 实现超时

2. **进度报告**
   * 对于长时间操作，使用进度令牌
   * 增量报告进度
