> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.wiki/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP 快速开始

> 5分钟内构建您的第一个 Model Context Protocol 服务器

## 概述

本指南将带您快速构建一个简单的 MCP 服务器，让您了解 Model Context Protocol 的基本工作原理。

<Info>
  **前提条件**:

  * Python 3.8+ 或 Node.js 18+
  * 对 JSON-RPC 有基本了解（可选）
</Info>

## 选择开发语言

MCP 支持多种编程语言。选择您熟悉的语言开始：

<CardGroup cols={2}>
  <Card title="Python" icon="python" href="#python-实现">
    使用官方 Python SDK 快速开始
  </Card>

  <Card title="TypeScript" icon="code" href="#typescript-实现">
    使用官方 TypeScript SDK 开发
  </Card>
</CardGroup>

## Python 实现

### 第 1 步：安装 SDK

```bash theme={null}
pip install mcp
```

### 第 2 步：创建基本服务器

创建一个名为 `mcp_server.py` 的文件：

```python theme={null}
from mcp import McpServer, Resource, Tool
from mcp.types import TextContent

# 创建 MCP 服务器实例
server = McpServer("my-first-server")

@server.resource("greeting/{name}")
async def get_greeting(name: str) -> Resource:
    """返回个性化问候消息"""
    content = f"Hello, {name}! Welcome to MCP!"
    return Resource(
        uri=f"greeting/{name}",
        name=f"Greeting for {name}",
        mimeType="text/plain",
        text=content
    )

@server.tool("calculate")
async def calculate(expression: str) -> str:
    """计算简单的数学表达式"""
    try:
        result = eval(expression)  # 注意：生产环境请使用安全的计算方法
        return f"计算结果: {expression} = {result}"
    except Exception as e:
        return f"计算错误: {str(e)}"

if __name__ == "__main__":
    server.run()
```

### 第 3 步：运行服务器

```bash theme={null}
python mcp_server.py
```

## TypeScript 实现

### 第 1 步：安装 SDK

```bash theme={null}
npm install @modelcontextprotocol/sdk
# 或者使用 yarn
yarn add @modelcontextprotocol/sdk
```

### 第 2 步：创建基本服务器

创建一个名为 `server.ts` 的文件：

```typescript theme={null}
import { McpServer } from '@modelcontextprotocol/sdk';

const server = new McpServer({
  name: 'my-first-server',
  version: '1.0.0'
});

// 注册资源
server.resource('greeting/{name}', async (name: string) => {
  return {
    uri: `greeting/${name}`,
    name: `Greeting for ${name}`,
    mimeType: 'text/plain',
    text: `Hello, ${name}! Welcome to MCP!`
  };
});

// 注册工具
server.tool('calculate', {
  description: '计算简单的数学表达式',
  parameters: {
    type: 'object',
    properties: {
      expression: {
        type: 'string',
        description: '要计算的数学表达式'
      }
    },
    required: ['expression']
  }
}, async (args) => {
  try {
    const result = eval(args.expression); // 注意：生产环境请使用安全的计算方法
    return `计算结果: ${args.expression} = ${result}`;
  } catch (error) {
    return `计算错误: ${error.message}`;
  }
});

// 启动服务器
server.start();
```

### 第 3 步：运行服务器

```bash theme={null}
npx ts-node server.ts
# 或者先编译再运行
tsc server.ts && node server.js
```

## 测试您的服务器

### 使用 Claude Desktop 测试

1. 打开 Claude Desktop 应用
2. 在设置中配置您的 MCP 服务器：

```json theme={null}
{
  "mcpServers": {
    "my-first-server": {
      "command": "python",
      "args": ["path/to/your/mcp_server.py"]
    }
  }
}
```

3. 重启 Claude Desktop
4. 在对话中尝试：
   * `@greeting/Alice` - 获取问候资源
   * 要求计算 `2 + 2` - 使用计算工具

### 使用命令行测试

您也可以使用 MCP Inspector 工具：

```bash theme={null}
npx @modelcontextprotocol/inspector python mcp_server.py
```

## 下一步

恭喜！您已经创建了第一个 MCP 服务器。接下来可以：

<CardGroup cols={2}>
  <Card title="深入了解核心概念" icon="book" href="/concepts/overview">
    学习 MCP 的资源、工具和提示概念
  </Card>

  <Card title="探索更多示例" icon="code" href="/examples/file-system">
    查看实际的应用案例和代码示例
  </Card>

  <Card title="阅读实现指南" icon="wrench" href="/implementation/server-development">
    了解如何构建生产级的 MCP 服务器
  </Card>

  <Card title="安全最佳实践" icon="shield" href="/implementation/security">
    学习如何安全地部署 MCP 服务
  </Card>
</CardGroup>

## 故障排除

<AccordionGroup>
  <Accordion title="服务器无法启动">
    检查：

    * Python/Node.js 版本是否符合要求
    * 依赖是否正确安装
    * 端口是否被占用
  </Accordion>

  <Accordion title="Claude Desktop 无法连接">
    确保：

    * 配置文件格式正确
    * 文件路径正确
    * 重启了 Claude Desktop
  </Accordion>

  <Accordion title="工具调用失败">
    验证：

    * 工具参数定义正确
    * 函数实现没有错误
    * 返回值格式符合规范
  </Accordion>
</AccordionGroup>
