Skip to main content
Glama

search_and_replace

Find and replace text in Word documents to update content, correct errors, or standardize terminology across files.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYes
searchTextYes
replaceTextYes
matchCaseNo

Implementation Reference

  • Core handler function that implements the search and replace logic: reads document text using mammoth, performs regex replace, and rewrites the document using docx Packer.
    async searchAndReplace(filePath: string, options: SearchReplaceOptions): Promise<APIResponse> {
      try {
        const buffer = await fs.readFile(filePath);
        const result = await mammoth.extractRawText({ buffer });
        let content = result.value;
    
        const searchRegex = new RegExp(
          options.searchText,
          `g${options.matchCase ? '' : 'i'}`
        );
    
        const matches = content.match(searchRegex) || [];
        content = content.replace(searchRegex, options.replaceText);
    
        // 注意:这里需要重新创建文档,因为 mammoth 主要用于读取
        const doc = new Document({
          sections: [{
            children: [new Paragraph({ text: content })],
          }],
        });
    
        await Packer.toBuffer(doc).then((buffer) => {
          return fs.writeFile(filePath, buffer);
        });
    
        return {
          success: true,
          data: {
            matchCount: matches.length,
            preview: content.substring(0, 200) + '...',
          },
        };
      } catch (error) {
        const err = error as Error;
        return { success: false, error: `查找替换失败: ${err.message}` };
      }
    }
  • TypeScript interface defining the input options for the search_and_replace tool.
    export interface SearchReplaceOptions {
      searchText: string;
      replaceText: string;
      matchCase?: boolean;
    }
  • MCP server tool registration using Zod schema, with handler wrapper calling DocumentService.searchAndReplace.
    server.tool(
      "search_and_replace",
      {
        filePath: z.string(),
        searchText: z.string(),
        replaceText: z.string(),
        matchCase: z.boolean().optional(),
      },
      async (params) => {
        const result = await docService.searchAndReplace(params.filePath, {
          searchText: params.searchText,
          replaceText: params.replaceText,
          matchCase: params.matchCase,
        });
        return {
          content: [
            {
              type: "text",
              text: result.success 
                ? `替换完成: ${result.data.matchCount} 处匹配\n预览: ${result.data.preview}` 
                : result.error!,
            },
          ],
          isError: !result.success,
        };
      }
    );
  • src/server.ts:67-80 (registration)
    HTTP server tool registration in tools array with inline JSON schema, dispatched later to DocumentService.
    {
      name: 'search_and_replace',
      description: '查找并替换文本',
      parameters: {
        properties: {
          filePath: { type: 'string', description: '文档路径' },
          searchText: { type: 'string', description: '要查找的文本' },
          replaceText: { type: 'string', description: '替换为的文本' },
          matchCase: { type: 'boolean', description: '是否区分大小写' },
        },
        required: ['filePath', 'searchText', 'replaceText'],
        type: 'object',
      },
    },
Behavior1/5

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

Tool has no description.

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

Conciseness1/5

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

Tool has no description.

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

Completeness1/5

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

Tool has no description.

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

Parameters1/5

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

Tool has no description.

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

Purpose1/5

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

Tool has no description.

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

Usage Guidelines1/5

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

Tool has no description.

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/puchunjie/doc-tools-mcp'

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