Skip to main content
Glama

Get Knowledge File

get_knowledge_file

Retrieve complete knowledge documents with metadata and chapters for comprehensive review, backups, or migrations. Ensure full content access while optimizing large documents with chapter operations.

Instructions

Retrieve complete content of a knowledge document including all metadata and chapters.

When to use this tool:

  • Needing full document for comprehensive review

  • Backing up or exporting documents

  • Migrating content between projects

  • Loading small documents completely

Key features:

  • Returns complete document with all chapters

  • Includes metadata (title, keywords, introduction)

  • Preserves document structure

  • Full content access

You should:

  1. Consider using chapter operations for large documents

  2. Check document exists first

  3. Include .md extension in filename

  4. Be aware this loads entire document into memory

  5. Use chapter iteration for partial access

  6. Cache result if accessing multiple times

DO NOT use when:

  • Only need specific chapters (use get_chapter)

  • Document is very large (use chapter operations)

  • Just need to search content (use search_knowledge)

Returns: {success: bool, document?: object, error?: str}

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYesKnowledge file name (must include .md extension)
project_idYesThe project identifier

Implementation Reference

  • Async handler function that implements the get_knowledge_file tool logic: locates the project and file, reads content, parses metadata and chapters, handles errors, and formats the response.
    async getKnowledgeFileAsync(params: {
      project_id: z.infer<typeof secureProjectIdSchema>;
      filename: z.infer<typeof secureFilenameSchema>;
    }): Promise<string> {
      const context = this.createContext('get_knowledge_file', params);
    
      try {
        const { project_id, filename } = params;
        const projectInfo = await getProjectDirectoryAsync(this.storagePath, project_id);
    
        // Project doesn't exist - return error without creating ghost entry
        if (!projectInfo) {
          throw new MCPError(MCPErrorCode.PROJECT_NOT_FOUND, `Project ${project_id} not found`, {
            project_id,
            filename,
            traceId: context.traceId,
          });
        }
    
        const [originalId, projectPath] = projectInfo;
        const knowledgePath = join(projectPath, 'knowledge');
        const filePath = join(knowledgePath, filename);
    
        // Check if file exists and read it
        let content: string;
        try {
          content = await readFile(filePath, 'utf8');
        } catch (error) {
          if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
            throw new MCPError(
              MCPErrorCode.DOCUMENT_NOT_FOUND,
              `Knowledge file ${filename} not found in project ${originalId}`,
              { project_id, filename, traceId: context.traceId }
            );
          }
          throw error;
        }
    
        const [metadata, body] = parseDocument(content);
    
        // Parse chapters from body
        const chapters = body
          .split(/^## /m)
          .slice(1)
          .map((chapterText) => {
            const lines = chapterText.split('\n');
            const title = lines[0].trim();
            const content = lines.slice(1).join('\n').trim();
    
            return {
              title,
              content,
              summary: content.split('\n')[0].slice(0, 100) + '...',
            };
          });
    
        this.logSuccess('get_knowledge_file', { project_id, filename }, context);
        return this.formatSuccessResponse({
          document: {
            filename,
            metadata,
            full_content: body,
            chapters,
          },
        });
      } catch (error) {
        const mcpError =
          error instanceof MCPError
            ? error
            : new MCPError(
                MCPErrorCode.DOCUMENT_NOT_FOUND,
                `Failed to get knowledge file: ${error instanceof Error ? error.message : String(error)}`,
                {
                  project_id: params.project_id,
                  filename: params.filename,
                  traceId: context.traceId,
                }
              );
        this.logError(
          'get_knowledge_file',
          {
            project_id: params.project_id,
            filename: params.filename,
          },
          mcpError,
          context
        );
        return this.formatErrorResponse(mcpError, context);
      }
    }
  • Registers the 'get_knowledge_file' tool with the MCP server, specifying title, description, input schema, and handler delegation.
    server.registerTool(
      'get_knowledge_file',
      {
        title: 'Get Knowledge File',
        description: TOOL_DESCRIPTIONS.get_knowledge_file,
        inputSchema: {
          project_id: secureProjectIdSchema.describe('The project identifier'),
          filename: secureFilenameSchema.describe('Knowledge file name (must include .md extension)'),
        },
      },
      async ({ project_id, filename }) => {
        const result = await knowledgeHandler.getKnowledgeFileAsync({ project_id, filename });
        return {
          content: [
            {
              type: 'text',
              text: result,
            },
          ],
        };
      }
    );
  • Defines the detailed natural language description and usage instructions for the get_knowledge_file tool, referenced in the registration.
      get_knowledge_file: `Retrieve complete content of a knowledge document including all metadata and chapters.
    
    When to use this tool:
    - Needing full document for comprehensive review
    - Backing up or exporting documents
    - Migrating content between projects
    - Loading small documents completely
    
    Key features:
    - Returns complete document with all chapters
    - Includes metadata (title, keywords, introduction)
    - Preserves document structure
    - Full content access
    
    You should:
    1. Consider using chapter operations for large documents
    2. Check document exists first
    3. Include .md extension in filename
    4. Be aware this loads entire document into memory
    5. Use chapter iteration for partial access
    6. Cache result if accessing multiple times
    
    DO NOT use when:
    - Only need specific chapters (use get_chapter)
    - Document is very large (use chapter operations)
    - Just need to search content (use search_knowledge)
    
    Returns: {success: bool, document?: object, error?: str}`,
Behavior4/5

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

With no annotations provided, the description carries full burden and adds valuable behavioral context beyond basic functionality. It discloses memory implications ('loads entire document into memory'), performance considerations for large documents, caching advice, and prerequisites like checking document existence. However, it doesn't mention error handling or rate limits, leaving some gaps.

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 well-structured with clear sections (purpose, usage guidelines, features, recommendations, exclusions, returns) and front-loaded key information. While comprehensive, some sentences could be more concise (e.g., 'Returns complete document with all chapters' and 'Full content access' are somewhat redundant). Overall, it's efficient but has minor verbosity.

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

Completeness4/5

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

For a tool with no annotations and no output schema, the description does an excellent job covering behavioral aspects, usage scenarios, and limitations. It explains what the tool returns (including the return structure) and provides practical guidance. The main gap is the lack of explicit error handling details, but otherwise it's nearly complete for this context.

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?

Schema description coverage is 100%, so the schema already documents both parameters (filename, project_id) with their constraints. The description adds minimal value beyond the schema: it reiterates the .md extension requirement (already in schema) and mentions checking document existence (not parameter-specific). This meets the baseline for high schema coverage.

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

Purpose5/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 with specific verbs ('retrieve complete content') and resources ('knowledge document'), distinguishing it from siblings like get_chapter (partial content) and search_knowledge (searching). It explicitly mentions what it returns (metadata, chapters, structure), making its scope unambiguous.

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

Usage Guidelines5/5

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

The description provides explicit guidance with dedicated sections: 'When to use this tool' lists four specific scenarios, 'You should' offers six actionable recommendations, and 'DO NOT use when' names three alternatives (get_chapter, chapter operations, search_knowledge). This clearly defines when to use this tool versus siblings.

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

Related 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/sven-borkert/knowledge-mcp'

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