> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/mcp.md).

# 如何将 MCP 服务器与本地 LLM 一起使用

了解如何通过截图将 MCP 服务器连接到开源 AI 模型。

本分步指南将向你展示如何连接 **模型上下文协议（MCP）** 服务器到本地 LLM，例如 [Qwen](/docs/zh/mo-xing/qwen3.6.md) 或 [Gemma](/docs/zh/mo-xing/gemma-4.md)，这样你运行的任何模型都可以通过 MCP 调用外部工具和服务。 将 MCP 连接到本地模型后，它就能安全地使用你的本地文件、应用、数据库和工具，而不只是依赖记忆进行聊天，从而构建一个更实用、更私密、可互换的 AI 助手，并且能够作用于你的真实环境。

我们将使用开源仓库 [Unsloth](https://github.com/unslothai/unsloth) 和 [llama.cpp](#llama.cpp-guide) ，因为它们是本地模型推理/部署的流行框架。MCP 适用于本地 GGUF 模型以及云端 [提供商模型](/docs/zh/ji-cheng/connections.md). **我们还会展示如何使用** [**多个 MCP 服务器**](#using-multiple-mcp-servers) **。**

MCP 工具可与模型的其他能力协同工作，例如 [代码执行](/docs/zh/xin/studio/chat.md#code-execution) 和 [网页搜索](/docs/zh/xin/studio/chat.md#advanced-web-search)，因此单个模型可以在同一个对话线程中搜索网页、运行代码，并调用你连接的服务。

### 用例

一旦连接了 MCP 服务器，你就可以让本地模型执行许多自动化任务。下面是一些示例：

* **搜索文档：** “找到相关文档并总结设置步骤。” - 可以使用 Context7。
* **分析代码库：** “梳理这个仓库，并说明身份验证、计费和数据访问分别发生在哪里。” - 可使用 GitHub 官方 MCP 和 GitMCP 来分析仓库。
* **使用嵌入向量搜索网页** - Exa 的 MCP 服务器可用于具备上下文嵌入支持的语义网页搜索。
* **调试网站 UI** - 可使用 Playwright 和 Chrome DevTools MCP 服务器来驱动网站并查找问题修复方案。

### 快速开始

我们将介绍两种将你设备上的本地模型连接到 MCP 服务器的方法。两种方法都使用开源包： [Unsloth](https://github.com/unslothai/unsloth) 和 [llama.cpp](llama.cpphttps://github.com/ggml-org/llama.cpp) 用于运行、提供服务并部署你的模型。

<a href="/docs/zh/ji-chu-zhi-shi/mcp.md#unsloth-guide" class="button primary">Unsloth MCP 指南</a><a href="/pages/10191e6f82adfd362724184fd4ff98deb38d6ee5#llama.cpp-guide" class="button primary">Llama.cpp MCP 指南</a>

### 🦥 Unsloth 指南

在这个示例中，我们将使用 Unsloth 将任意本地模型连接到 MCP 服务器，例如 [Qwen3.6](/docs/zh/mo-xing/qwen3.6.md) 或 [Gemma 4](/docs/zh/mo-xing/gemma-4.md) ，包括以下 MCP 服务器： [Vercel](https://mcp.vercel.com), [Context7](https://context7.com/), [Exa](https://exa.ai/) 和 [Hugging Face](https://huggingface.co/docs/hub/en/agents-mcp)。然后我们会问模型它能用它做什么。同样的步骤适用于任何 MCP 服务器。

{% stepper %}
{% step %}

#### 设置 Unsloth

最简单的入门方式是安装 [Unsloth Desktop](/docs/zh/desktop.md) 应用。它支持 [MacOS](/docs/zh/kuai-su-kai-shi/install/mac.md)、Linux、 [Windows](/docs/zh/kuai-su-kai-shi/install/windows-installation.md), [NVIDIA](/docs/zh/kuai-su-kai-shi/install/pip-install.md), [AMD](/docs/zh/kuai-su-kai-shi/install/amd.md)、Intel 以及 CPU 配置。

<a href="https://unsloth.ai/download" class="button primary" data-icon="down-to-bracket">下载 Unsloth</a>

* <i class="fa-apple">:apple:</i> [下载 macOS 版本](https://unsloth.ai/download/mac)
* <i class="fa-windows">:windows:</i> [下载 Windows 版本](https://unsloth.ai/download/windows)
* <i class="fa-linux">:linux:</i> [下载 Linux 版本](https://unsloth.ai/download/linux)

或者，如果你更喜欢手动安装：

**MacOS、Linux、WSL：**

```bash
curl -fsSL https://unsloth.ai/install.sh | sh
```

**Windows PowerShell：**

```bash
irm https://unsloth.ai/install.ps1 | iex
```

[请看这里](/docs/zh/desktop.md#get-started) 以获取详细说明。
{% endstep %}

{% step %}

#### **启用 MCP**

点击聊天工具栏中的“MCP”。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FqNVeCtCvYRMqKT9sSZey%2Fimage.png?alt=media&amp;token=9755a1cc-8118-40ba-ba1f-3b9ac0ef773d" alt=""><figcaption></figcaption></figure>

Unsloth Studio 默认支持 Context7、Exa 和 Hugging Face 的 MCP。开启 Exa [网页搜索](/docs/zh/xin/studio/chat.md#advanced-web-search) 会禁用我们已有的默认搜索工具。
{% endstep %}

{% step %}

#### **添加自定义 MCP 服务器**

要添加 Vercel MCP 服务器，点击“Add custom MCP”，你会看到一个弹窗：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FaO9zf15MX1jWL7nOmdyK%2Fimage.png?alt=media&amp;token=8ae977f0-8388-414c-9fbd-ae1efff464f2" alt=""><figcaption></figcaption></figure>

填写服务器详情：

1. **显示名称**：一个友好的标签，例如 `Vercel`.
2. **URL**：服务器的基础端点，例如 `https://mcp.vercel.com`.
3. 在下面选择一种认证方式。

{% tabs %}
{% tab title="OAuth 登录" %}
对于需要基于浏览器认证的服务器（GitHub、Linear、Vercel 等），请开启 **使用 OAuth 登录**。首次连接时会打开浏览器窗口，以便你授权 Unsloth。
{% endtab %}

{% tab title="自定义请求头" %}
对于使用令牌认证的服务器，请关闭 OAuth，然后点击 **添加请求头** 位于 **自定义请求头**下方。添加一个 `Authorization` 请求头，并填入你的令牌：

```
Authorization: Bearer <your-token>
```

{% endtab %}
{% endtabs %}

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FbgCzTby2rF3qgleWLNXA%2Fmcp-server-added.png?alt=media&amp;token=8095e37e-a4fa-4857-a5aa-0562af526eca" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### **测试并添加**

点击 **测试连接** 以确认 Unsloth 可以访问该服务器。一旦成功，点击 **添加服务器** 以保存。

如果 **测试连接** 失败，请检查 URL 是否为服务器的基础端点（而不是文档页面），以及你的认证方式是否正确。请参阅下面的故障排除。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FJeR2x79EkJaG4jYuOiBt%2Fmcp-add-server.png?alt=media&amp;token=38c4fdee-130f-415b-8c5d-e906f13c1555" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### **验证工具已加载**

该服务器现在会出现在 MCP Servers 列表中。Unsloth 会自动获取其工具并显示确认信息，例如 *已刷新“Vercel”（18 个工具）*.

每个服务器都提供以下控制项： **切换** 其开/关， **刷新** 其工具， **编辑** 它，或 **删除** 它。请确保服务器的开关和 **Use MCP Servers** 总开关都已开启，然后关闭对话框。

启用后它会高亮显示。你也可以再次点击它们来禁用。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FgunafFRR6EdrF0xXjIuG%2Fimage.png?alt=media&amp;token=3a91e79f-33d0-44da-a7a3-ded37a34b594" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### **在聊天中使用**

从 **选择模型** 下拉菜单中选择任意模型并开始聊天。当你的请求需要时，模型现在可以自行调用服务器工具。

上面，一个本地 `gemma-4-E2B-it-GGUF` 被询问 *“你能使用 Vercel MCP 服务器吗？”* 并报告了它可以执行的操作：管理项目、分析日志、列出团队、生成访问链接、检查域名，以及搜索 Vercel 的文档。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FoenMZ3aZx2yUX9ueAbmy%2Fmcp-chat-usecase.png?alt=media&amp;token=4284a8da-e77f-4961-8154-742cd75e4b01" alt=""><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

#### 使用多个 MCP 服务器

如果调用多个 MCP 服务器，比如 3 个，会怎样？我们将使用 Unsloth Studio 默认提供的 Exa、Context7 和 Hugging Face MCP 服务器，并全部启用。

如果你问“Unsloth 支持 Qwen 微调吗”，Exa 会提供很详细的信息：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FbqfXsWpuNJksyX2cLgfz%2Fimage.png?alt=media&amp;token=9f66e3e9-0e78-4016-853d-a7a8b63c4d25" alt=""><figcaption></figcaption></figure>

然后继续追问“搜索 Unsloth 文档，看看如何做这个”，这时会使用 Context7 获取文档：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FrPFQ90O4o8SIydVhDndx%2Fimage.png?alt=media&amp;token=35a48ee5-974b-45de-aba9-e9fb1e7833dd" alt=""><figcaption></figcaption></figure>

然后输入“在 Hugging Face 上搜索 unsloth/Qwen 模型”，Hugging Face 的 MCP 服务器就会被调用：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F9KPBtO3VFxC6Y9e4Hl0d%2Fimage.png?alt=media&amp;token=1c1757dc-4ccb-424f-b98b-29ae173df757" alt=""><figcaption></figcaption></figure>

#### 另一个具体用例示例

一旦服务器连接成功，就可以用自然语言让模型做实际工作。下面是几个使用 Vercel 服务器的示例：

* **调试失败的构建**: *“拉取我最近一次部署的构建日志，并告诉我为什么失败了。”*
* **检查部署状态**: *“列出我最近的部署及其状态。”*
* **搜索文档**: *“搜索 Vercel 文档，看看如何设置自定义域名。”*
* **域名研究**: *“ `myproject.dev` 可用吗，价格是多少？”*

### 🦙 Llama.cpp 指南

{% stepper %}
{% step %}

#### 安装或构建 llama.cpp

**macOS：**

```bash
brew install llama.cpp
```

或者对于 **Linux、Windows、WSL** ，从源码构建：

```bash
git clone https://github.com/ggml-org/llama.cpp
cmake -S llama.cpp -B llama.cpp/build -DCMAKE_BUILD_TYPE=Release
cmake --build llama.cpp/build --config Release -j --target llama-server llama-cli
```

{% endstep %}

{% step %}

#### 使用 GGUF 启动 llama-server

在这个示例中我们使用 [Gemma 4](/docs/zh/mo-xing/gemma-4.md) E4B GGUF：

```bash
llama-server \
  -hf unsloth/gemma-4-E4B-it-GGUF:UD-Q4_K_XL \
  --alias local \
  --host 127.0.0.1 \
  --port 8080 \
  --no-ui \
  --temp 1.0 \
  --top-p 0.95 \
  --top-k 64 \
  --reasoning off
```

对于更大的 Gemma 4 26B-A4B 模型：

```bash
llama-server \
  -hf unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_M \
  --alias local \
  --host 127.0.0.1 \
  --port 8080 \
  --no-ui \
  --temp 1.0 \
  --top-p 0.95 \
  --top-k 64 \
  --reasoning off
```

如需更多推理参数调整，请参阅我们的 [Gemma 4 指南](/docs/zh/mo-xing/gemma-4.md).

你可以测试服务器：

```bash
curl http://127.0.0.1:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer none" \
  -d '{
    "model": "local",
    "messages": [{"role": "user", "content": "Say hello in one sentence."}]
  }'
```

{% endstep %}

{% step %}

#### 创建 MCP 文件系统沙箱

```bash
mkdir -p ~/mcp-workspace
cd ~/mcp-workspace
pwd
```

复制绝对路径。为你的 MCP 主机创建一个单独的项目文件夹：

```bash
mkdir -p ~/llama-mcp
cd ~/llama-mcp
```

创建 `server_config.json`:

{% code expandable="true" %}

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/ABSOLUTE/PATH/TO/mcp-workspace"
      ],
      "env": {}
    }
  }
}
```

{% endcode %}

将路径替换为你真实的工作区路径。IBM 的 `mcp-cli` 文档使用同样的 `server_config.json` 结构和相同的 `npx -y @modelcontextprotocol/server-filesystem /path/to/allowed/files` 文件系统配置。
{% endstep %}

{% step %}

#### 针对 llama.cpp 运行一个终端 MCP 主机

使用 IBM 的 `mcp-cli`；它是一个带聊天模式、工具发现以及自定义 OpenAI 兼容提供商支持的命令行 MCP 客户端/主机。其文档推荐使用 `uvx mcp-cli --help`，支持项目 `server_config.json`，并可通过 `--api-base` 和 `--api-key`.

`mcp-cli` 需要一个配置文件才能启动。因此有必要增加一步来创建它。例如：

{% code title="" expandable="true" %}

```bash
mkdir -p ~/.chuk_llm
cat > ~/.chuk_llm/config.yaml <<'YAML'
openai_compatible:
  client_class: "chuk_llm.llm.providers.openai_client:OpenAILLMClient"
  default_model: "local"
  models: ["*"]
YAML
```

{% endcode %}

然后运行：

```bash
uvx mcp-cli \
  --provider llamacpp \
  --api-base http://127.0.0.1:8080/v1 \
  --api-key none \
  --model local \
  --server filesystem \
  --config-file server_config.json
```

然后尝试：

```
列出文件系统工作区中的文件。
```

然后：

```
创建 hello.txt，写入一句问候，然后再读回它。
```

`mcp-cli` 默认启用了工具调用确认，因此在工具执行前你应该会看到提示。

**完整代码示例：**

{% code expandable="true" %}

```bash
# 终端 1
llama-server -hf unsloth/gemma-4-E4B-it-GGUF:UD-Q4_K_XL \
  --alias local --host 127.0.0.1 --port 8080 --no-ui \
  --temp 1.0 --top-p 0.95 --top-k 64 \
  --chat-template-kwargs '{"enable_thinking":false}'

# 终端 2，在包含 server_config.json 的文件夹中
uvx mcp-cli \
  --provider llamacpp \
  --api-base http://127.0.0.1:8080/v1 \
  --api-key none \
  --model local \
  --server filesystem \
  --config-file server_config.json
```

{% endcode %}
{% endstep %}
{% endstepper %}

### 具有远程访问或局域网访问的本地 MCP 服务器

除了 `http(s)://` URL 之外， **URL 或可执行文件** 字段也接受本地命令，例如 `npx`, `uvx` ，或者服务器二进制文件的路径，其参数写在 **参数** 行中。这些本地（stdio）服务器作为你电脑上的一个程序运行。

当 **远程访问** 或 **局域网访问** 在设置中开启时（或 Unsloth 以 `--secure`启动时），Unsloth 可被其他设备访问，因此本地命令会被关闭，保存时会显示：

{% code collapsedlinecount="10" %}

```
当远程访问开启时，本地命令会被禁用，因为该服务器可从本机之外访问。
```

{% endcode %}

你仍然可以通过两种方式使用本地 MCP 服务器：

1. **在你自己的机器上通过 HTTP 运行服务器（推荐）。** 许多 MCP 服务器本身就可以提供 HTTP 服务。将其启动并绑定到 `127.0.0.1` ，这样只有这台计算机可以访问它，然后把其地址作为 URL 添加。例如，对于 [osmmcp](https://github.com/nervsystems/osmmcp):

   <pre class="language-bash" data-collapsed-line-count="10"><code class="lang-bash">osmmcp --enable-http --http-only --http-addr 127.0.0.1:7082
   </code></pre>

   然后添加 `http://127.0.0.1:7082/mcp` 到 MCP 对话框中。这适用于开启远程访问的 Unsloth Desktop 和 Studio。请在运行 Unsloth 的那台计算机上运行 MCP 服务器，而不是在你浏览所用的设备上；对于 [Docker](/docs/zh/kuai-su-kai-shi/install/docker.md), `127.0.0.1` 来说，容器本身就是目标，因此要在容器内启动服务器（`docker exec`）。对于只支持 stdio 的服务器，可以使用类似 [mcp-proxy](https://github.com/sparfenyuk/mcp-proxy) 的 stdio-to-HTTP 桥接工具来完成相同工作，例如 `mcp-proxy --port=8099 uvx mcp-server-fetch`，然后添加 `http://127.0.0.1:8099/mcp`.
2. **显式允许本地命令（Studio）。** 使用你自己设置的变量启动 Studio，即使开启远程访问或局域网访问，本地命令仍保持启用：

   <pre class="language-bash" data-collapsed-line-count="10"><code class="lang-bash">UNSLOTH_STUDIO_ALLOW_STDIO_MCP=1 unsloth studio
   </code></pre>

   在 Windows PowerShell 中： `$env:UNSLOTH_STUDIO_ALLOW_STDIO_MCP = "1"; unsloth studio`.

{% hint style="warning" %}
使用方案 2 时，任何能通过网络登录你的 Studio 的人都可以通过 MCP 服务器在你的电脑上运行程序。只有在你信任的网络上并使用强密码时才应使用它，且优先选择方案 1。
{% endhint %}

### 故障排除

如果服务器连接失败或其工具没有出现，请检查 URL 是否为服务器的基础端点（例如 `https://mcp.vercel.com`），而不是文档或控制台页面。对于 OAuth 服务器，请在浏览器登录窗口打开时完成登录；对于基于令牌的服务器，请验证 `Authorization` 请求头以及令牌是否有效。

如果在保存本地命令时出现“当远程访问开启时，本地命令被禁用”，请参阅 [具有远程访问或局域网访问的本地 MCP 服务器](#local-mcp-servers-with-remote-access-or-lan-access).

点击 **刷新** 如果连接后工具没有显示出来，请确保单个服务器开关和 **Use MCP Servers** 总开关都已开启。

### 安全说明

只连接你信任的 MCP 服务器。审查所请求的权限，并保持人工确认开启，适用于读取私密数据、更改部署、购买域名或修改项目的操作。将 MCP 服务器与网页搜索或其他工具结合使用时尤其要小心，因为提示注入内容可能会尝试触发不必要的工具调用。

### 热门 MCP 服务器

下面列出了一些你可以连接的热门且有用的 MCP 服务器：

| MCP 服务器             | 最适合                   | 有用之处                                                                                                                             |
| ------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| **GitHub MCP**      | 仓库、问题、PR、代码搜索、Actions | 官方 GitHub MCP，支持远程和本地设置，涵盖仓库、问题、拉取请求、Actions、代码安全等。([GitHub](https://github.com/github/github-mcp-server))                       |
| **Context7**        | 最新的库文档和示例             | 为编程助手获取当前、按版本区分的文档，而不是依赖过时的训练数据。使用 `https://mcp.context7.com/mcp`. ([GitHub](https://github.com/upstash/context7))               |
| **Notion MCP**      | 文档、笔记、任务、项目知识         | 适合使用 Notion 进行规格说明、PRD、路线图或笔记的团队。托管 MCP 可以读取和写入工作区内容。([Notion 开发者](https://developers.notion.com/guides/mcp/overview))           |
| **Slack MCP**       | 团队对话搜索                | 让 AI 工具查询 Slack 消息、频道、文件、线程和成员信息；操作取决于权限。([Slack](https://slack.com/help/articles/48855576908307-Guide-to-the-Slack-MCP-server)) |
| **Linear MCP**      | 问题、项目、产品工作流           | 用于查找、创建和更新 Linear 问题、项目、评论及相关对象的官方远程 MCP。([Linear](https://linear.app/changelog/2025-05-01-mcp))                                 |
| **Vercel MCP**      | 部署、日志、文档、域名           | 适用于前端/网页工作流：检查部署、日志、文档和项目上下文。请先检查客户端兼容性。([Vercel](https://vercel.com/docs/agent-resources/vercel-mcp?utm_source=chatgpt.com))    |
| **Sentry MCP**      | 生产环境调试                | 帮助智能体在有人参与的开发工作流中检查 Sentry 问题、追踪、错误和性能数据。([GitHub](https://github.com/getsentry/sentry-mcp))                                     |
| **文件系统 / 本地文件 MCP** | 本地项目文件                | 适用于本地 LLM 设置，通常通过 `stdio`。参考服务器最好仅视为示例或起点。([GitHub](https://github.com/modelcontextprotocol/servers))                            |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/zh/ji-chu-zhi-shi/mcp.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
