AI——OpenCode + Python打造飞书表格MCP服务器
前言本文将带你创建一个基于 Python 的 MCP 服务器它封装了读取飞书表格的逻辑。系统Windows环境准备OpenCode、Python网上都有安装教程自己搜一下一、前置准备1. 飞书开放平台创建应用打开飞书开放平台 → 新建「企业内部应用」开通权限sheets:readonly电子表格只读权限获取凭证App ID、App Secret2. 获取飞书文档信息表格文档ID从 Excel 链接中获取工作表IDsheet对应的 ID例如下面链接中9999999999999999999就是文档ID66666就是sheetIDhttps://f9gdjfow59.feishu.cn/sheets/9999999999999999999?sheet666663. 使用lark-cli读取文档信息安装 CLI (如果尚未安装):npm install -g larksuite/cli登录授权:首次使用需要扫码登录让 CLI 获取操作你飞书账号的权限。lark-cli config init lark-cli auth login --recommend读取文档lark-cli sheets read --spreadsheet-token 文档ID --sheet-id 文档中的sheetId“如图二、初始化Python项目新建文件夹mcp-feishu-server# 安装uv python -m pip install uv -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn # 安装 mcp 库 pip install mcp -i https://pypi.tuna.tsinghua.edu.cn/simple # 初始化一个 Python 项目 uv init三、编写MCP脚本通过命令 where lark-cli 找到lark-cli.cmd绝对路径替换下面的路径import os import json import subprocess from mcp.server.fastmcp import FastMCP # 初始化 MCP 服务器 mcp FastMCP(feishu-excel-mcp) # # ⚙️ 配置区域 # LARK_CLI_PATH rlark-cli.cmd绝对路径 mcp.tool() def read_feishu_sheet(spreadsheet_id: str, sheet_id: str, output_path: str) - str: 使用 lark-cli 读取飞书表格数据并保存为 JSON 文件。 Args: spreadsheet_id: 飞书电子表格的文档 ID。 sheet_id: 要读取的工作表 ID。 output_path: 输出文件的完整路径。 try: # 1. 检查输出目录是否存在不存在则创建 output_dir os.path.dirname(output_path) if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) print(f已创建输出目录: {output_dir}) # 2. 构造命令 (使用列表模式避免转义问题) cmd [ LARK_CLI_PATH, # 使用绝对路径 sheets, read, --spreadsheet-token, spreadsheet_id, --sheet-id, sheet_id ] # 3. 执行命令 # 但通常 .cmd 文件可以直接执行。 result subprocess.run( cmd, capture_outputTrue, textTrue, encodingutf-8, timeout60 ) # 4. 处理结果 if result.returncode 0: # 成功获取数据 raw_content result.stdout.strip() # 尝试解析 JSON 以确保格式正确 (可选) try: json_data json.loads(raw_content) formatted_json json.dumps(json_data, indent4, ensure_asciiFalse) except json.JSONDecodeError: # 如果输出不是纯 JSON (比如包含日志)则直接保存原始输出 formatted_json raw_content # 写入文件 with open(output_path, w, encodingutf-8) as f: f.write(formatted_json) return f✅ 数据读取成功并已保存至:\n{output_path} else: # 命令执行失败 (例如权限不足、ID错误) error_msg result.stderr if result.stderr else result.stdout return f❌ lark-cli 执行失败 (代码: {result.returncode}):\n{error_msg} except Exception as e: return f❌ 系统执行出错: {str(e)} if __name__ __main__: mcp.run()四、配置 OpenCode告诉 OpenCode 如何找到并启动你刚刚创建的 MCP 服务器并且启动1. 找到 OpenCode 配置文件在 Windows 系统中路径通常是 C:\Users\你的用户名\.config\opencode\opencode.json2. 添加 MCP 服务器配置使用文本编辑器打开 opencode.json 文件并在其中添加一个 mcp 字段。配置 command 来使用 Python 运行你的 main.py 脚本{ $schema: https://opencode.ai/config.json, mcp: { feishu-excel: { type: local, command: [ pythonw, 根路径\\mcp-feishu-server\\main.py ], cwd: 根路径\\mcp-feishu-server, enabled: true } } }