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',
      },
    },

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