Skip to main content
Glama
tuskermanshu

Swagger MCP Server

by tuskermanshu

file_writer

Write content to files with automatic directory creation and append options for managing generated API code and documentation.

Instructions

Write content to the specified file path, with support for automatic directory creation

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYesComplete path of the file
contentYesContent to be written to the file
createDirsNoWhether to automatically create parent directories if they do not exist
appendNoWhether to append to an existing file instead of overwriting it
encodingNoFile encodingutf8

Implementation Reference

  • Core handler function that performs file writing: validates params, creates directories if needed, appends or overwrites content, retrieves stats, handles errors.
    async writeFile(params: FileWriterParams): Promise<object> {
      try {
        const { filePath, content, createDirs, append, encoding } = params;
        
        // 确保父目录存在
        if (createDirs) {
          const dir = path.dirname(filePath);
          await fs.mkdir(dir, { recursive: true });
        }
        
        // 写入文件
        if (append) {
          await fs.appendFile(filePath, content, { encoding: encoding as BufferEncoding });
        } else {
          await fs.writeFile(filePath, content, { encoding: encoding as BufferEncoding });
        }
        
        // 获取文件信息
        const stats = await fs.stat(filePath);
        
        return {
          success: true,
          filePath,
          size: stats.size,
          created: stats.birthtime,
          modified: stats.mtime,
          message: `文件已${append ? '追加' : '写入'}: ${filePath}`,
        };
      } catch (error) {
        console.error('文件写入失败:', error);
        
        return {
          success: false,
          error: error instanceof Error ? error.message : String(error),
          filePath: params.filePath,
        };
      }
    }
  • Zod schema defining input parameters for the file_writer tool: filePath, content, createDirs, append, encoding.
    const fileWriterSchema = z.object({
      filePath: z.string().min(1).describe('Complete path of the file'),
      content: z.string().describe('Content to be written to the file'),
      createDirs: z.boolean().optional().default(true).describe('Whether to automatically create parent directories if they do not exist'),
      append: z.boolean().optional().default(false).describe('Whether to append to an existing file instead of overwriting it'),
      encoding: z.string().optional().default('utf8').describe('File encoding'),
    });
  • Class method `register` that registers the tool on the MCP server using server.tool with name, description, schema, and a wrapper async handler calling writeFile.
    register(server: McpServer): void {
      server.tool(
        this.name, 
        this.description,
        this.schema.shape,
        async (params) => {
          // 验证参数
          const result = await this.writeFile(params);
          
          // 返回符合MCP要求的格式
          return {
            ...result,
            content: [
              {
                type: "text",
                text: JSON.stringify(result, null, 2)
              }
            ]
          };
        }
      );
    }
  • src/index.ts:63-63 (registration)
    Registers the FileWriterTool instance on the MCP server in the main index entry point.
    new FileWriterTool().register(server);
  • Registers FileWriterTool (line 75) among other tools in the registerAllTools function used by the dedicated MCP tools server.
    function registerAllTools(server: McpServer): void {
      const tools = [
        new SwaggerParserTool(),
        new OptimizedSwaggerParserTool(),
        new TypeScriptTypesGeneratorTool(),
        new ApiClientGeneratorTool(),
        new FileWriterTool(),
      ];
      
      for (const tool of tools) {
        tool.register(server);
        console.log(`✅ 已注册工具: ${tool.name}`);
      }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'automatic directory creation' which adds useful context beyond basic writing, but fails to address critical behavioral aspects: whether the operation overwrites existing files by default (though the schema shows append defaults to false), what happens on permission errors, whether it's idempotent, or what the return value looks like (no output schema). For a mutation tool with zero annotation coverage, this is insufficient.

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

Conciseness5/5

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

The description is a single, efficient sentence that immediately conveys the core functionality and key feature. Every word earns its place with no redundancy or fluff. It's appropriately sized for a tool with comprehensive schema documentation.

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?

For a file mutation tool with 5 parameters, no annotations, and no output schema, the description is inadequate. It doesn't address error conditions, permission requirements, idempotency, or return values. While the schema covers parameter definitions well, the description fails to provide the behavioral context needed for safe and effective tool invocation in the absence of annotations.

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 all 5 parameters thoroughly. The description adds minimal value beyond the schema - it mentions 'automatic directory creation' which corresponds to the createDirs parameter, but doesn't provide additional semantic context about when or why to use specific parameters. The baseline of 3 is appropriate when the schema does the heavy lifting.

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 verb 'write' and resource 'content to the specified file path', making the purpose unambiguous. It distinguishes itself from sibling tools like template-save or template-get by focusing on raw file operations rather than template management. However, it doesn't explicitly differentiate from potential file-related siblings that might exist in other contexts.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. While it mentions 'automatic directory creation' as a feature, it doesn't specify scenarios where this tool is preferred over other file operations or template management tools in the sibling list. No exclusions or prerequisites are mentioned.

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/tuskermanshu/swagger-mcp-server'

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