Skip to main content
Glama

获取知识库目录

get-yuque-toc

Retrieve the complete table of contents structure for Yuque knowledge bases to view document hierarchies, titles, and slugs for organized navigation.

Instructions

获取语雀知识库的完整目录结构(TOC)。

可以查看知识库中所有文档的层级结构、标题和 slug。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
namespaceNo知识库命名空间 (例如: username/repo),如果未提供则使用默认命名空间

Implementation Reference

  • The main execution handler for the 'get-yuque-toc' tool. It validates the namespace, fetches the book metadata and TOC using API helpers, formats the output as Markdown tree, and returns it in the MCP content format.
    async ({ namespace }) => {
      try {
        const finalNamespace = namespace || YUQUE_CONFIG.namespace;
    
        if (!finalNamespace) {
          return {
            content: [
              {
                type: "text",
                text: `错误: 请提供知识库命名空间。\n\n示例: "username/repo"`,
              },
            ],
          };
        }
    
        if (!isValidNamespace(finalNamespace)) {
          return {
            content: [
              {
                type: "text",
                text: `错误: 命名空间格式无效。\n\n命名空间应该是 "username/repo" 的格式。`,
              },
            ],
          };
        }
    
        // 获取知识库信息
        const book = await fetchYuqueBook(finalNamespace, YUQUE_CONFIG);
        if (!book) {
          return {
            content: [
              {
                type: "text",
                text: `错误: 无法获取知识库 ${finalNamespace}。\n\n请检查命名空间是否正确,以及是否有访问权限。`,
              },
            ],
          };
        }
    
        // 获取目录
        const toc = await fetchYuqueToc(finalNamespace, YUQUE_CONFIG);
    
        if (toc.length === 0) {
          return {
            content: [
              {
                type: "text",
                text: `知识库 "${book.name}" 暂无文档。`,
              },
            ],
          };
        }
    
        // 格式化输出
        let output = `# 知识库: ${book.name}\n\n`;
        output += `**命名空间**: ${book.namespace}\n`;
        output += `**描述**: ${book.description || "无"}\n`;
        output += `**文档数量**: ${book.items_count}\n`;
        output += `**链接**: https://www.yuque.com/${book.namespace}\n\n`;
        output += `---\n\n`;
        output += formatTocTree(toc);
    
        return {
          content: [
            {
              type: "text",
              text: output,
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `错误: ${error instanceof Error ? error.message : "未知错误"}`,
            },
          ],
        };
      }
    }
  • src/index.ts:210-305 (registration)
    The registration of the 'get-yuque-toc' tool using McpServer.registerTool, including title, description, input schema, and handler reference.
    server.registerTool(
      "get-yuque-toc",
      {
        title: "获取知识库目录",
        description: `获取语雀知识库的完整目录结构(TOC)。
    
    可以查看知识库中所有文档的层级结构、标题和 slug。`,
        inputSchema: {
          namespace: z
            .string()
            .optional()
            .describe("知识库命名空间 (例如: username/repo),如果未提供则使用默认命名空间"),
        },
      },
      async ({ namespace }) => {
        try {
          const finalNamespace = namespace || YUQUE_CONFIG.namespace;
    
          if (!finalNamespace) {
            return {
              content: [
                {
                  type: "text",
                  text: `错误: 请提供知识库命名空间。\n\n示例: "username/repo"`,
                },
              ],
            };
          }
    
          if (!isValidNamespace(finalNamespace)) {
            return {
              content: [
                {
                  type: "text",
                  text: `错误: 命名空间格式无效。\n\n命名空间应该是 "username/repo" 的格式。`,
                },
              ],
            };
          }
    
          // 获取知识库信息
          const book = await fetchYuqueBook(finalNamespace, YUQUE_CONFIG);
          if (!book) {
            return {
              content: [
                {
                  type: "text",
                  text: `错误: 无法获取知识库 ${finalNamespace}。\n\n请检查命名空间是否正确,以及是否有访问权限。`,
                },
              ],
            };
          }
    
          // 获取目录
          const toc = await fetchYuqueToc(finalNamespace, YUQUE_CONFIG);
    
          if (toc.length === 0) {
            return {
              content: [
                {
                  type: "text",
                  text: `知识库 "${book.name}" 暂无文档。`,
                },
              ],
            };
          }
    
          // 格式化输出
          let output = `# 知识库: ${book.name}\n\n`;
          output += `**命名空间**: ${book.namespace}\n`;
          output += `**描述**: ${book.description || "无"}\n`;
          output += `**文档数量**: ${book.items_count}\n`;
          output += `**链接**: https://www.yuque.com/${book.namespace}\n\n`;
          output += `---\n\n`;
          output += formatTocTree(toc);
    
          return {
            content: [
              {
                type: "text",
                text: output,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `错误: ${error instanceof Error ? error.message : "未知错误"}`,
              },
            ],
          };
        }
      }
    );
  • Zod-based input schema for the tool, defining the optional 'namespace' parameter.
    inputSchema: {
      namespace: z
        .string()
        .optional()
        .describe("知识库命名空间 (例如: username/repo),如果未提供则使用默认命名空间"),
    },
  • Helper function that makes the API request to retrieve the TOC (table of contents) for a Yuque knowledge base.
    export async function fetchYuqueToc(
      namespace: string,
      config: YuqueConfig
    ): Promise<YuqueTocItem[]> {
      try {
        const url = `${config.baseUrl}/api/v2/repos/${namespace}/toc`;
    
        const response = await request(url, {
          method: "GET",
          headers: buildHeaders(config),
        });
    
        if (response.statusCode === 200) {
          const result = (await response.body.json()) as YuqueApiResponse<YuqueTocItem[]>;
          return result.data || [];
        } else {
          const errorData = (await response.body.json()) as YuqueError;
          console.error("Yuque API error:", errorData);
          return [];
        }
      } catch (error) {
        console.error("Error fetching Yuque TOC:", error);
        return [];
      }
    }
  • Helper function that fetches metadata for the Yuque knowledge base (book).
    export async function fetchYuqueBook(
      namespace: string,
      config: YuqueConfig
    ): Promise<YuqueBook | null> {
      try {
        const url = `${config.baseUrl}/api/v2/repos/${namespace}`;
    
        const response = await request(url, {
          method: "GET",
          headers: buildHeaders(config),
        });
    
        if (response.statusCode === 200) {
          const result = (await response.body.json()) as YuqueApiResponse<YuqueBook>;
          return result.data;
        } else {
          const errorData = (await response.body.json()) as YuqueError;
          console.error("Yuque API error:", errorData);
          return null;
        }
      } catch (error) {
        console.error("Error fetching Yuque book:", error);
        return null;
      }
    }
  • Helper function that formats the TOC array into a hierarchical Markdown tree structure.
    export function formatTocTree(toc: YuqueTocItem[]): string {
      let output = `# 知识库目录\n\n`;
    
      const buildTree = (items: YuqueTocItem[], parentUuid: string = "", depth: number = 0): string => {
        let result = "";
        const children = items.filter((item) => (item.parent_uuid || "") === parentUuid);
    
        children.forEach((item) => {
          const indent = "  ".repeat(depth);
          const prefix = depth === 0 ? "#".repeat(Math.min(depth + 2, 6)) + " " : "- ";
    
          if (item.type === "TITLE") {
            result += `${indent}${prefix}**${item.title}**\n`;
          } else if (item.type === "DOC") {
            result += `${indent}${prefix}${item.title} \`[${item.slug}]\`\n`;
          } else if (item.type === "LINK") {
            result += `${indent}${prefix}[${item.title}](${item.url})\n`;
          }
    
          // 递归处理子节点
          if (item.uuid) {
            result += buildTree(items, item.uuid, depth + 1);
          }
        });
    
        return result;
      };
    
      output += buildTree(toc);
    
      return output;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It describes what the tool does (gets TOC structure) but lacks critical behavioral details: it doesn't mention whether this is a read-only operation, potential rate limits, authentication requirements, error conditions, or the format of the returned data. For a tool with no annotation coverage, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with two sentences that directly address the tool's function and capabilities. The first sentence states the core purpose, and the second adds useful context about what can be viewed. There's no wasted language, though it could be slightly more structured with explicit usage guidance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has no annotations, no output schema, and the description lacks behavioral details, the description is incomplete. It adequately explains what the tool does but fails to address how it behaves, what it returns, or important contextual factors. For a tool that presumably returns structured data, the absence of output information is particularly problematic.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with the single parameter 'namespace' fully documented in the schema. The description doesn't add any parameter-specific information beyond what's in the schema. According to the rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in the description, which applies here.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: '获取语雀知识库的完整目录结构(TOC)' (Get the complete table of contents structure for Yuque knowledge base). It specifies the verb ('获取' - get) and resource ('目录结构' - TOC structure), and distinguishes it from siblings by focusing on hierarchical structure rather than listing or searching documents. However, it doesn't explicitly differentiate from 'list-yuque-docs' which might also provide some structural information.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by mentioning '可以查看知识库中所有文档的层级结构、标题和 slug' (Can view the hierarchical structure, titles, and slugs of all documents in the knowledge base), suggesting it's for understanding document organization. However, it doesn't explicitly state when to use this tool versus alternatives like 'list-yuque-docs' or 'search-yuque-docs', nor does it provide any exclusions or prerequisites.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/saoqixiaomm/yuque-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server