Context7 Claude Code 技能:resolve-library-id 与 query-docs 的库文档检索工作流解析
Context7 的 Claude Code 插件通过 context7-mcp 技能(Skill),让 AI 在回答库/框架相关问题时自动调用 MCP 工具拉取最新文档,而非依赖过时的训练数据。本文以 SKILL.md 为主体,完整还原其激活条件、四步文档获取工作流和关键行为约束,并结合 MCP 服务器源码 与 AI SDK 工具实现 深入解析每个步骤的底层调用链与参数设计。
技能定义与激活场景
context7-mcp 技能以 YAML frontmatter 声明其元信息,位于 skills/context7-mcp/SKILL.md:
---
name: context7-mcp
description: This skill should be used when the user asks about libraries, frameworks,
API references, or needs code examples. Activates for setup questions, code generation
involving libraries, or mentions of specific frameworks like React, Vue, Next.js,
Prisma, Supabase, etc.
---
技能的核心指令是一句话:当用户询问库、框架或需要代码示例时,使用 Context7 获取当前文档,而非依赖训练数据。
激活触发条件
文档明确列出了四类触发场景:
| 用户行为 | 示例 |
|---|---|
| 提出安装/配置问题 | "How do I configure Next.js middleware?" |
| 请求涉及库的代码生成 | "Write a Prisma query for..." |
| 需要 API 参考 | "What are the Supabase auth methods?" |
| 提及具体框架名称 | React、Vue、Svelte、Express、Tailwind 等 |
这些触发条件与 MCP 服务器在 index.ts 中声明的 instructions 字段高度一致。服务器描述中明确指出:无论用户问的是 API 语法、配置、版本迁移、库特定调试、安装说明还是 CLI 工具用法,即使涉及 React、Next.js、Prisma、Express、Tailwind、Django、Spring Boot 等知名库,也应使用 Context7 而非 Web 搜索。同时列出了不适用的场景:重构、从零写脚本、业务逻辑调试、代码审查和通用编程概念。
技能在插件中的位置
该技能是 Claude Code 插件 四个组件之一:
- MCP Server — 连接 Claude Code 与 Context7 文档服务
- Skills — 自动触发文档检索(即本文主体)
- Agents — 专用的 docs-researcher 智能体,用于隔离上下文
- Commands — /context7:docs 手动查询命令
这四者共享同一套 resolve-library-id → query-docs 工作流,技能负责"自动触发",命令负责"手动触发",Agent 负责"上下文隔离"。
四步文档获取工作流
技能文档将文档检索流程拆分为四个严格顺序的步骤。下面逐步展开,并对照源码验证每个参数的实际行为。
第一步:解析库 ID(resolve-library-id)
调用 resolve-library-id 工具,传入两个参数:
libraryName:从用户问题中提取的库名称query:要在该库文档中查找的内容(用于提升相关性排序)
在 MCP 服务器源码 中,该工具注册为 resolve-library-id,其输入 Schema 使用 z.preprocess(aliasArgs(GLOBAL_ALIASES), ...) 包裹。aliasArgs 函数的作用是将 LLM 常见的"幻觉参数名"映射回规范字段——例如 userQuery 和 question 都会被自动改写为 query,避免 Zod 校验失败。这一设计从源码注释中得到确认:
// Map of canonical arg name -> hallucinated aliases that should be rewritten
// to it. LLM clients often echo phrasing from tool descriptions instead of
// the literal schema keys, which trips Zod validation before the tool runs.
const GLOBAL_ALIASES: AliasMap = {
query: ["userQuery", "question"],
};
在 AI SDK 版本 中,该工具的实现更加精简。execute 函数内部调用 client.searchLibrary(query, libraryName, { type: "txt" }),其中 type: "txt" 指定返回纯文本格式,方便 LLM 消费。工具描述(来自 prompts/system.ts)中强调了几个关键约束:
- 必须在调用
queryDocs之前调用,除非用户直接提供了/org/project格式的 ID - 库名应使用官方拼写(如
'Next.js'而非'nextjs') - 每个问题最多调用 3 次
- 不得在 query 中包含 API 密钥、密码等敏感信息
返回结果格式
成功时返回匹配库列表,每条记录包含以下字段(与 文档说明 一致):
- Title: React Documentation
- Context7-compatible library ID: /reactjs/react.dev
- Description: The library for web and native user interfaces
- Code Snippets: 1250
- Source Reputation: High
- Benchmark Score: 98
- Versions: 19.0.0, 18.3.1, 18.2.0
----------
- Title: React Native
- Context7-compatible library ID: /facebook/react-native
- Description: A framework for building native applications using React
- Code Snippets: 890
- Source Reputation: High
- Benchmark Score: 95
- Versions: 0.76.0, 0.75.4
未找到匹配时返回:
No libraries found matching "unknown-lib". Try a different search term or check the library name.
第二步:选择最佳匹配
从解析结果中,依据以下维度选择最合适的库:
- 名称精确度:与用户所问名称的精确匹配优先
- 基准分数(Benchmark Score):分数越高表示文档质量越好(满分 100)
- 版本偏好:如果用户提到了版本号(如 "React 19"),优先选择带版本后缀的 ID
MCP 服务器源码中的工具描述对此有完整阐述:
Selection Process:
1. Analyze the query to understand what library/package the user is looking for
2. Return the most relevant match based on:
- Name similarity to the query (exact matches prioritized)
- Description relevance to the query's intent
- Documentation coverage (prioritize libraries with higher Code Snippet counts)
- Source reputation (consider libraries with High or Medium reputation more authoritative)
- Benchmark Score: Quality indicator (100 is the highest score)
此外还要求:对模糊查询应先向用户请求澄清,而非做"最佳猜测"匹配。
第三步:获取文档(query-docs)
调用 query-docs 工具,传入:
libraryId:选定的 Context7 库 ID,格式为/org/project或/org/project/version(例如/vercel/next.js)query:要查找的具体概念,限定为单一主题
多概念拆分原则是此步骤的核心规则。当用户问题跨越多个独立概念(如"路由 + 认证 + 缓存")时,必须对每个概念分别调用 query-docs,使用相同的 libraryId 但不同的 query。文档原文解释了原因:
合并查询会稀释排序精度,导致每个主题都只返回浅层结果。除非问题本身是关于这些概念之间的交互关系。
这一约束在 query-docs.ts 的 query 字段描述中被完整保留,包含正反示例:
Good: 'How to set up authentication with JWT in Express.js'
Good: 'React useEffect cleanup function examples'
Bad (too vague): 'auth' or 'hooks'
Bad (too broad): 'routing and auth and caching in Next.js'
在 MCP 服务器源码中,query-docs 工具额外配置了工具作用域的参数别名 QUERY_DOCS_ALIASES:
const QUERY_DOCS_ALIASES: AliasMap = {
libraryId: ["context7CompatibleLibraryID", "libraryID", "libraryName"],
};
这意味着如果 LLM 将 libraryName(本应属于 resolve-library-id 的参数)误传到 query-docs,服务器会自动将其映射为 libraryId。这种容错设计从源码注释得到确认:"LLM 客户端经常从工具描述中照抄措辞而非使用字面 schema 键名。"
版本锁定
Library ID 支持版本限定后缀:
/vercel/next.js # 最新版本
/vercel/next.js/v14.3.0-canary.87 # 指定版本
/supabase/supabase/v2.45.0 # 指定版本
commands/docs.md 中的示例进一步展示了版本锁定的实际用法:
/context7:docs /vercel/next.js/v15.1.8 middleware
/context7:docs /facebook/react/v19.0.0 use hook
返回结果格式
成功时返回纯文本文档片段(来自 query-docs 文档):
# Server Components
Server Components let you write UI that can be rendered and optionally cached on the server.
## Example
```tsx
async function ServerComponent() {
const data = await fetchData();
return <div>{data}</div>;
}
You can import Server Components into Client Components...
失败时返回诊断提示,引导使用 `resolveLibraryId` 重新获取有效 ID:
No documentation found for library "/invalid/library". This might have happened because you used an invalid Context7-compatible library ID. Use 'resolveLibraryId' to get a valid ID.
### 第四步:使用文档
将获取的文档融入最终回答,具体要求:
- **用当前准确信息回答用户问题**
- **包含文档中相关的代码示例**
- **在必要时注明库版本**
这一约束在 [prompts/system.ts](https://gitcode.com/gh_mirrors/co/context7/blob/4e980f6b494d6f970cc5ec1df417ba684b2f6e0b/packages/tools-ai-sdk/src/prompts/system.ts?utm_source=gitcode_repo_files) 的 `SYSTEM_PROMPT` 中同样被强调:"Cite your sources by mentioning the library ID used"——始终注明使用了哪个库 ID。
## 关键行为约束
技能文档和源码共同定义了几条硬性规则,确保工作流不会失控:
### 每次调用最多 3 次
[RESOLVE_LIBRARY_ID_DESCRIPTION](https://gitcode.com/gh_mirrors/co/context7/blob/4e980f6b494d6f970cc5ec1df417ba684b2f6e0b/packages/tools-ai-sdk/src/prompts/system.ts?utm_source=gitcode_repo_files) 和 `QUERY_DOCS_DESCRIPTION` 中都明确写入:
IMPORTANT: Do not call this tool more than 3 times per question. If you cannot find what you need after 3 calls, use the best result you have.
这条约束防止 LLM 陷入无限重试循环,在 [AI SDK 工具测试](https://gitcode.com/gh_mirrors/co/context7/blob/4e980f6b494d6f970cc5ec1df417ba684b2f6e0b/packages/tools-ai-sdk/src/index.test.ts?utm_source=gitcode_repo_files) 中也有对应验证。
### 单一概念查询
"每次 query 只涉及一个概念"是贯穿所有组件的核心原则。[docs-researcher agent](https://gitcode.com/gh_mirrors/co/context7/blob/4e980f6b494d6f970cc5ec1df417ba684b2f6e0b/plugins/claude/context7/agents/docs-researcher.md?utm_source=gitcode_repo_files) 的技能描述中重复了这条规则,[commands/docs.md](https://gitcode.com/gh_mirrors/co/context7/blob/4e980f6b494d6f970cc5ec1df417ba684b2f6e0b/plugins/claude/context7/commands/docs.md?utm_source=gitcode_repo_files) 的 usage 说明中也将 query 参数标注为 "run the command once per distinct concept, unless asking how they interact"。
### 官方来源优先
当解析结果中存在多个匹配时,优先选择官方/主包,而非社区 fork。这一原则在技能文档、MCP 工具描述和 [AI SDK 系统提示](https://gitcode.com/gh_mirrors/co/context7/blob/4e980f6b494d6f970cc5ec1df417ba684b2f6e0b/packages/tools-ai-sdk/src/prompts/system.ts?utm_source=gitcode_repo_files) 中一致出现。
### 跳过 resolve 的条件
工具描述明确指出:如果用户已在查询中直接提供了 `/org/project` 或 `/org/project/version` 格式的 ID,可以跳过 `resolve-library-id`,直接调用 `query-docs`。这在 [query-docs 文档的"Direct Library ID"示例](https://gitcode.com/gh_mirrors/co/context7/blob/4e980f6b494d6f970cc5ec1df417ba684b2f6e0b/docs/agentic-tools/ai-sdk/tools/query-docs.mdx?utm_source=gitcode_repo_files) 中有代码演示:
```typescript
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "Using /vercel/next.js, explain middleware",
tools: {
queryDocs: queryDocs(), // 无需 resolveLibraryId
},
stopWhen: stepCountIs(3),
});
在 AI SDK 中编程式复现相同工作流
上述四步工作流不仅限于 Claude Code 插件,还可通过 AI SDK 工具包 以编程方式在任意 AI SDK 应用中复现:
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "How do I use React Server Components?",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
两个工具函数均接受可选的 Context7ToolsConfig 配置对象,支持通过 apiKey 字段传入 API 密钥,未传入时自动读取 CONTEXT7_API_KEY 环境变量。对于多步骤的综合文档检索(如"Supabase 认证完整指南"),可增大 stopWhen 步数以允许模型多次调用 queryDocs:
stopWhen: stepCountIs(8) // 允许多次查询以收集综合文档
预构建的 Context7Agent 则封装了完整工作流,无需手动编排工具调用顺序。
与插件内其他组件的协作关系
技能并非孤立运行。在 Claude Code 插件 中,它与以下组件形成互补:
docs-researcher Agent(agents/docs-researcher.md)将同一套四步流程封装为独立子智能体,使用 sonnet 模型运行,目的是避免文档检索过程污染主对话上下文。用户可通过 "spawn docs-researcher to look up Supabase auth methods" 显式调用。
/context7:docs 命令(commands/docs.md)提供手动触发入口,支持库名或直接 ID 两种输入格式:
/context7:docs react hooks
/context7:docs /vercel/next.js/v15.1.8 app router
其内部逻辑与技能完全一致:以 / 开头的参数直接作为 Context7 ID 使用,否则先经 resolve-library-id 解析。
MCP 服务器(packages/mcp/src/index.ts)提供底层工具注册、参数校验和别名容错,支持 stdio 和 http 两种传输模式。通过 CONTEXT7_API_KEY 环境变量或 --api-key 命令行参数进行身份认证。
总结
context7-mcp 技能的核心价值在于将"文档检索"从 LLM 的自由发挥约束为一条确定性的两工具调用链:resolve-library-id 负责将自然语言库名映射为结构化 ID,query-docs 负责按单一概念拉取排名靠前的文档片段。配合版本锁定、官方来源优先、每轮最多 3 次调用等约束,该工作流在 Claude Code 插件、AI SDK 工具包 和 MCP 服务器 三处保持一致实现,确保无论在哪个客户端中运行,文档检索的行为和结果质量都是可预期的。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0622
Hy4-previewHy4 preview 是由腾讯混元团队研发的新一代混合专家(MoE)旗舰模型。模型总参数量 770B,每个 token 激活 49B,主干共包含78层,第一层采用标准 FFN,其余 77 层均为 MoE 结构,每层包含 256 个路由专家与 1 个共享专家,每个 token 激活 top-8 路由专家及共享专家。主干之外原生内置 1 层 MTP(总参数量 10B,激活 0.7B)以支持投机解码。Python00
GLM-5.3GLM-5.3 与 GLM-5.2 使用相同的基座模型——所有提升均来自后训练。与 GLM-5.2 相比,它在复杂编程和长程任务上的表现显著提升。Jinja00
GLM-5.3-FlashGLM-5.3-Flash (320B-A18B),是GLM-5系列的首个原生多模态模型。320B总参数,能力超过GLM-5.2Jinja00
Spark-X2.5-4BSpark-X2.5-4B 旨在让强大的 AI 更实用、更高效、更易获得。在广泛日常任务中表现强劲,涵盖对话、写作、翻译、推理、编码、工具调用以及智能体工作流,并在同等规模的开源模型中取得领先成绩。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00