@cortex-agent/server 2026.5.25-1 → 2026.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/defaults/config/thread-templates.json +28 -1
- package/defaults/hooks/cortex-md-injector.mjs +47 -31
- package/defaults/hooks/post-task-hook.mjs +6 -0
- package/defaults/hooks/task-status-check.mjs +8 -0
- package/defaults/mcp-config-slack.json +11 -0
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
- package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
- package/defaults/prompts/directives/manager.md +67 -0
- package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
- package/dist/agent-adapter/claude/adapter-tui.js +91 -12
- package/dist/agent-adapter/claude/adapter.js +11 -0
- package/dist/agent-adapter/claude/defaults.d.ts +30 -0
- package/dist/agent-adapter/claude/defaults.js +30 -0
- package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
- package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
- package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
- package/dist/agent-adapter/claude/spawn-args.js +49 -7
- package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
- package/dist/agent-adapter/claude/tmux-control.js +54 -8
- package/dist/agent-adapter/codex/adapter.js +1 -1
- package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
- package/dist/agent-adapter/pi/adapter.js +46 -19
- package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
- package/dist/agent-adapter/pi/agent-dir.js +53 -2
- package/dist/agent-adapter/pi/event-parser.js +13 -1
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
- package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
- package/dist/agent-adapter/pi/tool-shims.js +167 -140
- package/dist/agent-adapter/types.d.ts +7 -2
- package/dist/core/atomic-write.js +21 -0
- package/dist/core/config-generator.d.ts +10 -0
- package/dist/core/config-generator.js +28 -0
- package/dist/core/gateway-generator.d.ts +77 -7
- package/dist/core/gateway-generator.js +301 -29
- package/dist/core/icons.d.ts +68 -0
- package/dist/core/icons.js +67 -0
- package/dist/core/profile-generator.d.ts +6 -0
- package/dist/core/profile-generator.js +35 -7
- package/dist/core/running-executions.d.ts +51 -41
- package/dist/core/running-executions.js +120 -73
- package/dist/core/status-format.js +3 -2
- package/dist/core/task-parser.d.ts +3 -0
- package/dist/core/task-parser.js +3 -1
- package/dist/core/types/thread-types.d.ts +54 -8
- package/dist/domain/agents/facade.d.ts +18 -0
- package/dist/domain/agents/facade.js +26 -3
- package/dist/domain/agents/profile-manager.d.ts +11 -0
- package/dist/domain/agents/profile-manager.js +21 -2
- package/dist/domain/costs/codex-usage-monitor.js +2 -1
- package/dist/domain/costs/rate-limit-throttle.js +14 -2
- package/dist/domain/executions/registry.d.ts +24 -0
- package/dist/domain/executions/registry.js +38 -0
- package/dist/domain/mcp/core-server.js +15 -3
- package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
- package/dist/domain/mcp/feishu/bitable.js +168 -0
- package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
- package/dist/domain/mcp/feishu/block-types.js +127 -0
- package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
- package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
- package/dist/domain/mcp/feishu/client.d.ts +46 -0
- package/dist/domain/mcp/feishu/client.js +87 -0
- package/dist/domain/mcp/feishu/docx.d.ts +3 -0
- package/dist/domain/mcp/feishu/docx.js +163 -0
- package/dist/domain/mcp/feishu/drive.d.ts +23 -0
- package/dist/domain/mcp/feishu/drive.js +66 -0
- package/dist/domain/mcp/feishu/file.d.ts +14 -0
- package/dist/domain/mcp/feishu/file.js +107 -0
- package/dist/domain/mcp/feishu/index.d.ts +6 -0
- package/dist/domain/mcp/feishu/index.js +61 -0
- package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
- package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
- package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
- package/dist/domain/mcp/feishu/sheets.js +119 -0
- package/dist/domain/mcp/feishu/types.d.ts +26 -0
- package/dist/domain/mcp/feishu/types.js +38 -0
- package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
- package/dist/domain/mcp/feishu/user-auth.js +286 -0
- package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
- package/dist/domain/mcp/feishu/wiki.js +77 -0
- package/dist/domain/mcp/feishu-server.d.ts +2 -0
- package/dist/domain/mcp/feishu-server.js +33 -0
- package/dist/domain/mcp/server.d.ts +0 -1
- package/dist/domain/mcp/server.js +6 -25
- package/dist/domain/mcp/slack-server.d.ts +3 -0
- package/dist/domain/mcp/slack-server.js +46 -0
- package/dist/domain/mcp/tools/context.js +1 -1
- package/dist/domain/mcp/tools/schedule.d.ts +1 -1
- package/dist/domain/mcp/tools/schedule.js +6 -20
- package/dist/domain/mcp/tools/slack.js +20 -7
- package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
- package/dist/domain/mcp/tools/thread-ops.js +121 -0
- package/dist/domain/mcp/tools/time.d.ts +2 -0
- package/dist/domain/mcp/tools/time.js +66 -0
- package/dist/domain/mcp/tools/tui-ask.js +1 -1
- package/dist/domain/mcp/tools/tui-plan.js +2 -2
- package/dist/domain/mcp/tui-server.js +1 -0
- package/dist/domain/monitor/disk-monitor.js +2 -1
- package/dist/domain/monitor/gpu-monitor.js +2 -1
- package/dist/domain/remote/client-hot-reload.js +3 -2
- package/dist/domain/remote/client-manager.js +8 -6
- package/dist/domain/scheduling/job-registry.d.ts +4 -0
- package/dist/domain/scheduling/job-registry.js +1 -0
- package/dist/domain/scheduling/jobs/_shared.js +2 -1
- package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
- package/dist/domain/scheduling/jobs/sync-public.js +4 -3
- package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
- package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
- package/dist/domain/scheduling/jobs/task-archive.js +3 -2
- package/dist/domain/scheduling/jobs/task-dispatch.js +120 -10
- package/dist/domain/scheduling/schedule-command.js +16 -15
- package/dist/domain/scheduling/scheduler.d.ts +1 -1
- package/dist/domain/scheduling/scheduler.js +2 -1
- package/dist/domain/sessions/session-hooks.d.ts +2 -2
- package/dist/domain/sessions/session-hooks.js +19 -18
- package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
- package/dist/domain/sessions/session-lifecycle.js +44 -0
- package/dist/domain/system/install-cli.d.ts +7 -0
- package/dist/domain/system/install-cli.js +106 -0
- package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
- package/dist/domain/tasks/dispatch-utils.js +53 -4
- package/dist/domain/tasks/dispatcher.js +26 -0
- package/dist/domain/tasks/lint.js +28 -0
- package/dist/domain/tasks/mutator.d.ts +16 -3
- package/dist/domain/tasks/mutator.js +41 -12
- package/dist/domain/tasks/pending-tracker.js +6 -5
- package/dist/domain/tasks/system/task-cli.d.ts +2 -0
- package/dist/domain/tasks/system/task-cli.js +37 -6
- package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
- package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
- package/dist/domain/tasks/system/task-mutations.js +166 -8
- package/dist/domain/threads/contract.d.ts +17 -0
- package/dist/domain/threads/contract.js +59 -0
- package/dist/domain/threads/hook-runner.js +7 -6
- package/dist/domain/threads/index.d.ts +2 -0
- package/dist/domain/threads/index.js +3 -1
- package/dist/domain/threads/prompt-builder.d.ts +15 -1
- package/dist/domain/threads/prompt-builder.js +41 -2
- package/dist/domain/threads/runner.d.ts +6 -5
- package/dist/domain/threads/runner.js +128 -79
- package/dist/domain/threads/state-machine.d.ts +23 -21
- package/dist/domain/threads/state-machine.js +113 -54
- package/dist/domain/threads/template-loader.js +3 -2
- package/dist/domain/threads/tree.d.ts +45 -0
- package/dist/domain/threads/tree.js +171 -0
- package/dist/domain/tui-session/index.d.ts +2 -0
- package/dist/domain/tui-session/index.js +3 -0
- package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
- package/dist/domain/tui-session/tui-session-service.js +103 -0
- package/dist/domain/tui-session/types.d.ts +67 -0
- package/dist/domain/tui-session/types.js +4 -0
- package/dist/domain/ui-service/index.d.ts +5 -0
- package/dist/domain/ui-service/index.js +3 -0
- package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
- package/dist/domain/ui-service/mutate/executions.js +15 -0
- package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
- package/dist/domain/ui-service/mutate/schedules.js +39 -0
- package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
- package/dist/domain/ui-service/mutate/tasks.js +59 -0
- package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
- package/dist/domain/ui-service/mutate/threads.js +21 -0
- package/dist/domain/ui-service/query/cost.d.ts +3 -0
- package/dist/domain/ui-service/query/cost.js +6 -0
- package/dist/domain/ui-service/query/executions.d.ts +2 -0
- package/dist/domain/ui-service/query/executions.js +35 -0
- package/dist/domain/ui-service/query/projects.d.ts +2 -0
- package/dist/domain/ui-service/query/projects.js +30 -0
- package/dist/domain/ui-service/query/schedules.d.ts +2 -0
- package/dist/domain/ui-service/query/schedules.js +23 -0
- package/dist/domain/ui-service/query/sessions.d.ts +2 -0
- package/dist/domain/ui-service/query/sessions.js +35 -0
- package/dist/domain/ui-service/query/tasks.d.ts +2 -0
- package/dist/domain/ui-service/query/tasks.js +30 -0
- package/dist/domain/ui-service/query/threads.d.ts +2 -0
- package/dist/domain/ui-service/query/threads.js +27 -0
- package/dist/domain/ui-service/subscribe.d.ts +5 -0
- package/dist/domain/ui-service/subscribe.js +118 -0
- package/dist/domain/ui-service/types.d.ts +237 -0
- package/dist/domain/ui-service/types.js +5 -0
- package/dist/domain/ui-service/ui-service.d.ts +2 -0
- package/dist/domain/ui-service/ui-service.js +83 -0
- package/dist/entry/app.js +94 -5
- package/dist/entry/cli.d.ts +12 -0
- package/dist/entry/cli.js +122 -12
- package/dist/entry/feishu-login.d.ts +28 -0
- package/dist/entry/feishu-login.js +218 -0
- package/dist/entry/init.d.ts +25 -2
- package/dist/entry/init.js +211 -64
- package/dist/events/event-types.d.ts +14 -0
- package/dist/hooks/cortex-md-injector.mjs +47 -31
- package/dist/hooks/post-task-hook.mjs +6 -0
- package/dist/hooks/task-status-check.mjs +8 -0
- package/dist/orchestration/agent-runner.d.ts +2 -1
- package/dist/orchestration/agent-runner.js +55 -55
- package/dist/orchestration/conduit-queue.d.ts +18 -0
- package/dist/orchestration/conduit-queue.js +32 -0
- package/dist/orchestration/conversation-runner.d.ts +48 -0
- package/dist/orchestration/conversation-runner.js +109 -0
- package/dist/orchestration/dispatch-reconciler.js +8 -1
- package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
- package/dist/orchestration/interactions/ask-user-question.js +3 -3
- package/dist/orchestration/interactions/interaction-handlers.js +48 -17
- package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
- package/dist/orchestration/interactions/plan-handler.js +4 -3
- package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
- package/dist/orchestration/interactions/update-prompt.js +100 -0
- package/dist/orchestration/lifecycle.d.ts +4 -4
- package/dist/orchestration/lifecycle.js +24 -22
- package/dist/orchestration/orchestrator.d.ts +1 -1
- package/dist/orchestration/routing/commands/cancel.js +39 -47
- package/dist/orchestration/routing/commands/channel.js +24 -11
- package/dist/orchestration/routing/commands/cost.js +2 -1
- package/dist/orchestration/routing/commands/device.js +3 -2
- package/dist/orchestration/routing/commands/dispatch.js +6 -5
- package/dist/orchestration/routing/commands/index.d.ts +1 -1
- package/dist/orchestration/routing/commands/index.js +11 -10
- package/dist/orchestration/routing/commands/mode.js +19 -18
- package/dist/orchestration/routing/commands/nvtop.js +10 -9
- package/dist/orchestration/routing/commands/sendfile.js +7 -6
- package/dist/orchestration/routing/commands/session.d.ts +1 -1
- package/dist/orchestration/routing/commands/session.js +17 -33
- package/dist/orchestration/routing/commands/tail.js +4 -3
- package/dist/orchestration/routing/commands/task.js +4 -3
- package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
- package/dist/orchestration/routing/edit-handler.js +8 -7
- package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
- package/dist/orchestration/routing/message-router.d.ts +1 -1
- package/dist/orchestration/routing/message-router.js +9 -9
- package/dist/orchestration/routing/webhook.js +233 -2
- package/dist/orchestration/status-helpers.d.ts +5 -1
- package/dist/orchestration/status-helpers.js +7 -6
- package/dist/orchestration/thread-callback.d.ts +67 -0
- package/dist/orchestration/thread-callback.js +465 -0
- package/dist/orchestration/thread-executor.d.ts +22 -1
- package/dist/orchestration/thread-executor.js +85 -36
- package/dist/platform/adapter.d.ts +6 -2
- package/dist/platform/adapters/composite-adapter.d.ts +89 -0
- package/dist/platform/adapters/composite-adapter.js +318 -0
- package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
- package/dist/platform/adapters/feishu-output-stream.js +274 -36
- package/dist/platform/adapters/feishu.d.ts +50 -5
- package/dist/platform/adapters/feishu.js +370 -116
- package/dist/platform/adapters/index.d.ts +24 -3
- package/dist/platform/adapters/index.js +89 -11
- package/dist/platform/adapters/project-conduits.d.ts +9 -0
- package/dist/platform/adapters/project-conduits.js +42 -0
- package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
- package/dist/platform/adapters/slack-project-conduits.js +6 -40
- package/dist/platform/adapters/slack.d.ts +9 -2
- package/dist/platform/adapters/slack.js +83 -39
- package/dist/platform/adapters/tui/index.d.ts +9 -0
- package/dist/platform/adapters/tui/index.js +10 -0
- package/dist/platform/adapters/tui/ports.d.ts +20 -0
- package/dist/platform/adapters/tui/ports.js +4 -0
- package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
- package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
- package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
- package/dist/platform/adapters/tui/tui-connection.js +53 -0
- package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
- package/dist/platform/adapters/tui/tui-gateway.js +919 -0
- package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
- package/dist/platform/adapters/tui/tui-notifications.js +60 -0
- package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
- package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
- package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
- package/dist/platform/adapters/tui/tui-transcript.js +56 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +2 -1
- package/dist/platform/interactive-builder.js +3 -2
- package/dist/platform/output-stream.d.ts +5 -0
- package/dist/platform/testing.d.ts +7 -11
- package/dist/platform/testing.js +18 -15
- package/dist/platform/tool-trace.js +15 -5
- package/dist/platform/tui/protocol.d.ts +355 -0
- package/dist/platform/tui/protocol.js +199 -0
- package/dist/platform/types.d.ts +12 -3
- package/dist/store/execution-repo.d.ts +6 -1
- package/dist/store/execution-repo.js +13 -3
- package/dist/store/hook-sync.d.ts +18 -0
- package/dist/store/hook-sync.js +92 -0
- package/dist/store/outbound-queue.js +2 -2
- package/dist/store/profile-repo.js +3 -2
- package/dist/store/schedule-repo.d.ts +1 -8
- package/dist/store/session-registry-repo.d.ts +9 -1
- package/dist/store/session-registry-repo.js +19 -3
- package/dist/store/session-repo.d.ts +14 -0
- package/dist/store/session-repo.js +23 -0
- package/dist/store/thread-repo.d.ts +3 -0
- package/dist/store/thread-repo.js +49 -2
- package/dist/store/version-migrations.js +95 -0
- package/dist/tui/App.d.ts +27 -0
- package/dist/tui/App.js +219 -0
- package/dist/tui/components/AskUserModal.d.ts +11 -0
- package/dist/tui/components/AskUserModal.js +364 -0
- package/dist/tui/components/ConfirmModal.d.ts +12 -0
- package/dist/tui/components/ConfirmModal.js +31 -0
- package/dist/tui/components/Dashboard.d.ts +23 -0
- package/dist/tui/components/Dashboard.js +80 -0
- package/dist/tui/components/DashboardCostTab.d.ts +7 -0
- package/dist/tui/components/DashboardCostTab.js +16 -0
- package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
- package/dist/tui/components/DashboardExecutionsTab.js +94 -0
- package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
- package/dist/tui/components/DashboardSchedulesTab.js +124 -0
- package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
- package/dist/tui/components/DashboardTasksTab.js +200 -0
- package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
- package/dist/tui/components/DashboardThreadsTab.js +81 -0
- package/dist/tui/components/Header.d.ts +11 -0
- package/dist/tui/components/Header.js +5 -0
- package/dist/tui/components/InputBox.d.ts +10 -0
- package/dist/tui/components/InputBox.js +19 -0
- package/dist/tui/components/MessageRow.d.ts +7 -0
- package/dist/tui/components/MessageRow.js +10 -0
- package/dist/tui/components/Notifications.d.ts +19 -0
- package/dist/tui/components/Notifications.js +72 -0
- package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
- package/dist/tui/components/PlanFeedbackModal.js +161 -0
- package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
- package/dist/tui/components/ProjectSwitcher.js +43 -0
- package/dist/tui/components/SessionPicker.d.ts +14 -0
- package/dist/tui/components/SessionPicker.js +34 -0
- package/dist/tui/components/SidePanel.d.ts +19 -0
- package/dist/tui/components/SidePanel.js +8 -0
- package/dist/tui/components/StatusLine.d.ts +10 -0
- package/dist/tui/components/StatusLine.js +29 -0
- package/dist/tui/components/Transcript.d.ts +13 -0
- package/dist/tui/components/Transcript.js +56 -0
- package/dist/tui/hooks/useDashboardData.d.ts +32 -0
- package/dist/tui/hooks/useDashboardData.js +104 -0
- package/dist/tui/hooks/useKeybindings.d.ts +19 -0
- package/dist/tui/hooks/useKeybindings.js +87 -0
- package/dist/tui/hooks/useMutate.d.ts +22 -0
- package/dist/tui/hooks/useMutate.js +56 -0
- package/dist/tui/hooks/useNotifications.d.ts +28 -0
- package/dist/tui/hooks/useNotifications.js +70 -0
- package/dist/tui/hooks/useTranscript.d.ts +39 -0
- package/dist/tui/hooks/useTranscript.js +265 -0
- package/dist/tui/hooks/useWsClient.d.ts +29 -0
- package/dist/tui/hooks/useWsClient.js +69 -0
- package/dist/tui/index.d.ts +2 -0
- package/dist/tui/index.js +210 -0
- package/dist/tui/logic.d.ts +16 -0
- package/dist/tui/logic.js +49 -0
- package/dist/tui/render/markdown.d.ts +10 -0
- package/dist/tui/render/markdown.js +38 -0
- package/dist/tui/render/rich-blocks.d.ts +11 -0
- package/dist/tui/render/rich-blocks.js +24 -0
- package/dist/tui/ws-client.d.ts +44 -0
- package/dist/tui/ws-client.js +157 -0
- package/package.json +11 -3
- package/dist/orchestration/channel-queue.d.ts +0 -18
- package/dist/orchestration/channel-queue.js +0 -32
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// input: McpServer, Feishu LarkClient, route-context file path
|
|
2
|
+
// output: feishu_send_file tool registration
|
|
3
|
+
// pos: MCP tool for uploading files to Feishu
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import * as fs from 'fs';
|
|
7
|
+
import * as path from 'path';
|
|
8
|
+
import { guard, ok, unwrap } from './types.js';
|
|
9
|
+
function readRouteContext(routeContextFile) {
|
|
10
|
+
if (!routeContextFile)
|
|
11
|
+
return null;
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(fs.readFileSync(routeContextFile, 'utf8'));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function resolveReadableFilePath(filePathInput) {
|
|
20
|
+
const resolved = path.isAbsolute(filePathInput)
|
|
21
|
+
? filePathInput
|
|
22
|
+
: path.resolve(process.cwd(), filePathInput);
|
|
23
|
+
if (!fs.existsSync(resolved)) {
|
|
24
|
+
throw new Error(`File not found: ${resolved}`);
|
|
25
|
+
}
|
|
26
|
+
const stat = fs.statSync(resolved);
|
|
27
|
+
if (!stat.isFile()) {
|
|
28
|
+
throw new Error(`Not a file: ${resolved}`);
|
|
29
|
+
}
|
|
30
|
+
return { resolved, size: stat.size };
|
|
31
|
+
}
|
|
32
|
+
/** Strip the 'feishu:' prefix from a channel ID (tolerates already-bare values for back-compat).
|
|
33
|
+
* Multi-platform conduits carry the 'feishu:' prefix from FEISHU_CHANNEL env var;
|
|
34
|
+
* the Feishu OpenAPI expects bare channel IDs (e.g., oc_123abc).
|
|
35
|
+
* This mirrors FeishuAdapter._unwrap() behavior. */
|
|
36
|
+
function stripFeishuPrefix(channelId) {
|
|
37
|
+
const PREFIX = 'feishu:';
|
|
38
|
+
if (!channelId)
|
|
39
|
+
return channelId;
|
|
40
|
+
return channelId.startsWith(PREFIX) ? channelId.slice(PREFIX.length) : channelId;
|
|
41
|
+
}
|
|
42
|
+
/** Infer Feishu file type from file extension (used by the OpenAPI file.create call).
|
|
43
|
+
* Feishu API only supports specific file_type values:
|
|
44
|
+
* opus, mp4, pdf, doc, xls, ppt, stream
|
|
45
|
+
* For unsupported types, use 'stream' as a catch-all. */
|
|
46
|
+
function inferFeishuFileType(fileName) {
|
|
47
|
+
const ext = path.extname(fileName).toLowerCase();
|
|
48
|
+
const typeMap = {
|
|
49
|
+
'.pdf': 'pdf',
|
|
50
|
+
'.doc': 'doc',
|
|
51
|
+
'.xls': 'xls',
|
|
52
|
+
'.ppt': 'ppt',
|
|
53
|
+
'.mp4': 'mp4',
|
|
54
|
+
'.opus': 'opus',
|
|
55
|
+
};
|
|
56
|
+
// Feishu API doesn't support 'text', 'image', 'zip', 'rar', 'docx', 'xlsx', 'pptx'
|
|
57
|
+
// Use 'stream' as fallback for all unsupported types
|
|
58
|
+
return typeMap[ext] || 'stream';
|
|
59
|
+
}
|
|
60
|
+
export async function uploadFileToFeishu(client, { channel, filePath, fileName, title }) {
|
|
61
|
+
const { resolved, size } = resolveReadableFilePath(filePath);
|
|
62
|
+
const body = fs.readFileSync(resolved);
|
|
63
|
+
const uploadName = fileName || path.basename(resolved);
|
|
64
|
+
// Strip 'feishu:' prefix from channel ID for Feishu API compatibility
|
|
65
|
+
const bareChannel = stripFeishuPrefix(channel);
|
|
66
|
+
// Upload file to get file_key
|
|
67
|
+
const uploadRes = await client.im.v1.file.create({
|
|
68
|
+
data: {
|
|
69
|
+
file_type: inferFeishuFileType(uploadName),
|
|
70
|
+
file_name: uploadName,
|
|
71
|
+
file: body,
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
const fileKey = unwrap(uploadRes).file_key;
|
|
75
|
+
if (!fileKey)
|
|
76
|
+
throw new Error('Feishu file upload failed: no file_key returned');
|
|
77
|
+
// Send file message to channel
|
|
78
|
+
const msgContent = JSON.stringify({ file_key: fileKey });
|
|
79
|
+
await client.im.v1.message.create({
|
|
80
|
+
params: { receive_id_type: 'chat_id' },
|
|
81
|
+
data: {
|
|
82
|
+
receive_id: bareChannel,
|
|
83
|
+
msg_type: 'file',
|
|
84
|
+
content: msgContent,
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
return { path: resolved, fileName: uploadName, size };
|
|
88
|
+
}
|
|
89
|
+
export function registerFileTools(server, deps) {
|
|
90
|
+
server.tool('feishu_send_file', 'Upload a local file to Feishu. Use this when you need to share a file (document, image, archive, etc.) with users in a Feishu chat or channel.', {
|
|
91
|
+
file_path: z.string().describe('Local file path to upload'),
|
|
92
|
+
file_name: z.string().optional().describe('Optional filename override shown in Feishu'),
|
|
93
|
+
title: z.string().optional().describe('Optional file title shown in Feishu'),
|
|
94
|
+
channel: z.string().optional().describe('Optional chat/channel ID (uses route context if not provided)'),
|
|
95
|
+
}, async ({ file_path, file_name, title, channel: explicitChannel }) => guard(deps.client, async (client) => {
|
|
96
|
+
const channel = explicitChannel || (process.env.FEISHU_CHANNEL ?? '');
|
|
97
|
+
if (!channel)
|
|
98
|
+
throw new Error('No Feishu channel available (missing FEISHU_CHANNEL env or channel parameter)');
|
|
99
|
+
const uploaded = await uploadFileToFeishu(client, {
|
|
100
|
+
channel,
|
|
101
|
+
filePath: file_path,
|
|
102
|
+
fileName: file_name,
|
|
103
|
+
title,
|
|
104
|
+
});
|
|
105
|
+
return ok(`File uploaded: ${uploaded.fileName} (${uploaded.size} bytes)`);
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import type { FeishuToolDeps } from './types.js';
|
|
3
|
+
/** Tool names exposed by the cortex-feishu MCP server (kept in sync for verification). */
|
|
4
|
+
export declare const FEISHU_TOOL_NAMES: readonly string[];
|
|
5
|
+
export declare function registerFeishuTools(server: McpServer, deps: FeishuToolDeps): void;
|
|
6
|
+
export type { FeishuToolDeps } from './types.js';
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// input: MCP SDK, register*Tools modules, FeishuToolDeps
|
|
2
|
+
// output: registerFeishuTools — aggregate all feishu_* doc/wiki/bitable/sheets tools onto a server
|
|
3
|
+
// pos: Single entry the cortex-feishu MCP server calls to wire all Feishu tools
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { registerDocxTools } from './docx.js';
|
|
6
|
+
import { registerWikiTools } from './wiki.js';
|
|
7
|
+
import { registerBitableTools } from './bitable.js';
|
|
8
|
+
import { registerSheetsTools } from './sheets.js';
|
|
9
|
+
import { registerDriveTools } from './drive.js';
|
|
10
|
+
import { registerFileTools } from './file.js';
|
|
11
|
+
/** Tool names exposed by the cortex-feishu MCP server (kept in sync for verification). */
|
|
12
|
+
export const FEISHU_TOOL_NAMES = [
|
|
13
|
+
// file — send files to chats
|
|
14
|
+
'feishu_send_file',
|
|
15
|
+
// docx — cloud documents
|
|
16
|
+
'feishu_docx_create',
|
|
17
|
+
'feishu_docx_get_content',
|
|
18
|
+
'feishu_docx_list_blocks',
|
|
19
|
+
'feishu_docx_append',
|
|
20
|
+
'feishu_docx_insert',
|
|
21
|
+
'feishu_docx_update_block',
|
|
22
|
+
'feishu_docx_delete_blocks',
|
|
23
|
+
'feishu_docx_delete',
|
|
24
|
+
// wiki — knowledge base
|
|
25
|
+
'feishu_wiki_list_spaces',
|
|
26
|
+
'feishu_wiki_list_nodes',
|
|
27
|
+
'feishu_wiki_get_node',
|
|
28
|
+
'feishu_wiki_create_node',
|
|
29
|
+
'feishu_wiki_update_node_title',
|
|
30
|
+
// bitable — 多维表格
|
|
31
|
+
'feishu_bitable_create_app',
|
|
32
|
+
'feishu_bitable_delete_app',
|
|
33
|
+
'feishu_bitable_list_tables',
|
|
34
|
+
'feishu_bitable_create_table',
|
|
35
|
+
'feishu_bitable_delete_table',
|
|
36
|
+
'feishu_bitable_list_fields',
|
|
37
|
+
'feishu_bitable_create_field',
|
|
38
|
+
'feishu_bitable_list_records',
|
|
39
|
+
'feishu_bitable_create_records',
|
|
40
|
+
'feishu_bitable_update_records',
|
|
41
|
+
'feishu_bitable_delete_records',
|
|
42
|
+
// sheets — 电子表格
|
|
43
|
+
'feishu_sheets_create',
|
|
44
|
+
'feishu_sheets_delete',
|
|
45
|
+
'feishu_sheets_get',
|
|
46
|
+
'feishu_sheets_read_range',
|
|
47
|
+
'feishu_sheets_write_range',
|
|
48
|
+
'feishu_sheets_append_rows',
|
|
49
|
+
'feishu_sheets_add_sheet',
|
|
50
|
+
'feishu_sheets_delete_sheet',
|
|
51
|
+
// drive — sharing & permissions
|
|
52
|
+
'feishu_drive_set_link_share',
|
|
53
|
+
];
|
|
54
|
+
export function registerFeishuTools(server, deps) {
|
|
55
|
+
registerFileTools(server, deps);
|
|
56
|
+
registerDocxTools(server, deps);
|
|
57
|
+
registerWikiTools(server, deps);
|
|
58
|
+
registerBitableTools(server, deps);
|
|
59
|
+
registerSheetsTools(server, deps);
|
|
60
|
+
registerDriveTools(server, deps);
|
|
61
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Inline text style flags mirroring Feishu `text_element_style`. */
|
|
2
|
+
export interface InlineStyle {
|
|
3
|
+
bold?: boolean;
|
|
4
|
+
italic?: boolean;
|
|
5
|
+
strikethrough?: boolean;
|
|
6
|
+
inline_code?: boolean;
|
|
7
|
+
link?: {
|
|
8
|
+
url: string;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/** A Feishu inline element (text_run only — mentions/equations go via the blocks escape hatch). */
|
|
12
|
+
export interface TextElement {
|
|
13
|
+
text_run: {
|
|
14
|
+
content: string;
|
|
15
|
+
text_element_style?: InlineStyle;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** A Feishu docx block descriptor accepted by documentBlockChildren.create. */
|
|
19
|
+
export interface BlockDescriptor {
|
|
20
|
+
block_type: number;
|
|
21
|
+
[key: string]: unknown;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Parse a single line of inline markdown into Feishu text elements.
|
|
25
|
+
* Handles (with escaping): `**bold**`, `*italic*` / `_italic_`, `~~strike~~`,
|
|
26
|
+
* `` `code` ``, and `[label](url)`. Emphasis nests; inline code is opaque.
|
|
27
|
+
*/
|
|
28
|
+
export declare function parseInline(text: string, base?: InlineStyle): TextElement[];
|
|
29
|
+
/**
|
|
30
|
+
* Convert markdown into a flat list of Feishu docx block descriptors.
|
|
31
|
+
*
|
|
32
|
+
* Block-level (one markdown line = one block, except fenced code which spans
|
|
33
|
+
* lines): ATX headings `#`–`######` → heading1-6, `-`/`*` → bullet, `1.` →
|
|
34
|
+
* ordered, `- [ ]`/`- [x]` → todo, ```` ``` ```` fences → code (with language),
|
|
35
|
+
* `>` → quote, `---`/`***`/`___` → divider, everything else → text paragraph.
|
|
36
|
+
*
|
|
37
|
+
* Nesting (multi-level lists, callouts) and Feishu-only blocks (tables, images,
|
|
38
|
+
* colors, mentions) are out of scope here — use the raw `blocks` escape hatch.
|
|
39
|
+
*/
|
|
40
|
+
export declare function markdownToBlocks(md: string): BlockDescriptor[];
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// input: block-types (BlockType enum, key map, language map)
|
|
2
|
+
// output: markdownToBlocks(md) → Feishu docx block descriptor[] (block-level + inline styles)
|
|
3
|
+
// pos: Content authoring path for feishu_docx_* tools — shields agents from raw block JSON
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { BlockType, BLOCK_TYPE_KEY, headingBlockType, codeLanguageCode } from './block-types.js';
|
|
6
|
+
function mergeStyle(base, add) {
|
|
7
|
+
return { ...base, ...add };
|
|
8
|
+
}
|
|
9
|
+
function makeRun(content, style) {
|
|
10
|
+
if (Object.keys(style).length === 0) {
|
|
11
|
+
return { text_run: { content } };
|
|
12
|
+
}
|
|
13
|
+
return { text_run: { content, text_element_style: style } };
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Parse a single line of inline markdown into Feishu text elements.
|
|
17
|
+
* Handles (with escaping): `**bold**`, `*italic*` / `_italic_`, `~~strike~~`,
|
|
18
|
+
* `` `code` ``, and `[label](url)`. Emphasis nests; inline code is opaque.
|
|
19
|
+
*/
|
|
20
|
+
export function parseInline(text, base = {}) {
|
|
21
|
+
const out = [];
|
|
22
|
+
let buf = '';
|
|
23
|
+
const flush = () => {
|
|
24
|
+
if (buf) {
|
|
25
|
+
out.push(makeRun(buf, base));
|
|
26
|
+
buf = '';
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
let i = 0;
|
|
30
|
+
while (i < text.length) {
|
|
31
|
+
const c = text[i];
|
|
32
|
+
// Backslash escape — next char is literal.
|
|
33
|
+
if (c === '\\' && i + 1 < text.length) {
|
|
34
|
+
buf += text[i + 1];
|
|
35
|
+
i += 2;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
// Inline code — opaque, not re-parsed.
|
|
39
|
+
if (c === '`') {
|
|
40
|
+
const end = text.indexOf('`', i + 1);
|
|
41
|
+
if (end !== -1) {
|
|
42
|
+
flush();
|
|
43
|
+
out.push(makeRun(text.slice(i + 1, end), mergeStyle(base, { inline_code: true })));
|
|
44
|
+
i = end + 1;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
// Link [label](url).
|
|
49
|
+
if (c === '[') {
|
|
50
|
+
const close = text.indexOf(']', i + 1);
|
|
51
|
+
if (close !== -1 && text[close + 1] === '(') {
|
|
52
|
+
const paren = text.indexOf(')', close + 2);
|
|
53
|
+
if (paren !== -1) {
|
|
54
|
+
flush();
|
|
55
|
+
const label = text.slice(i + 1, close);
|
|
56
|
+
const url = text.slice(close + 2, paren);
|
|
57
|
+
out.push(...parseInline(label, mergeStyle(base, { link: { url } })));
|
|
58
|
+
i = paren + 1;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// Strong **…**.
|
|
64
|
+
if (text.startsWith('**', i)) {
|
|
65
|
+
const end = text.indexOf('**', i + 2);
|
|
66
|
+
if (end !== -1) {
|
|
67
|
+
flush();
|
|
68
|
+
out.push(...parseInline(text.slice(i + 2, end), mergeStyle(base, { bold: true })));
|
|
69
|
+
i = end + 2;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
// Strikethrough ~~…~~.
|
|
74
|
+
if (text.startsWith('~~', i)) {
|
|
75
|
+
const end = text.indexOf('~~', i + 2);
|
|
76
|
+
if (end !== -1) {
|
|
77
|
+
flush();
|
|
78
|
+
out.push(...parseInline(text.slice(i + 2, end), mergeStyle(base, { strikethrough: true })));
|
|
79
|
+
i = end + 2;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// Emphasis *…* or _…_.
|
|
84
|
+
if (c === '*' || c === '_') {
|
|
85
|
+
const end = text.indexOf(c, i + 1);
|
|
86
|
+
if (end > i + 1) {
|
|
87
|
+
flush();
|
|
88
|
+
out.push(...parseInline(text.slice(i + 1, end), mergeStyle(base, { italic: true })));
|
|
89
|
+
i = end + 1;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
buf += c;
|
|
94
|
+
i++;
|
|
95
|
+
}
|
|
96
|
+
flush();
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
function block(blockType, payload) {
|
|
100
|
+
return { block_type: blockType, [BLOCK_TYPE_KEY[blockType]]: payload };
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Convert markdown into a flat list of Feishu docx block descriptors.
|
|
104
|
+
*
|
|
105
|
+
* Block-level (one markdown line = one block, except fenced code which spans
|
|
106
|
+
* lines): ATX headings `#`–`######` → heading1-6, `-`/`*` → bullet, `1.` →
|
|
107
|
+
* ordered, `- [ ]`/`- [x]` → todo, ```` ``` ```` fences → code (with language),
|
|
108
|
+
* `>` → quote, `---`/`***`/`___` → divider, everything else → text paragraph.
|
|
109
|
+
*
|
|
110
|
+
* Nesting (multi-level lists, callouts) and Feishu-only blocks (tables, images,
|
|
111
|
+
* colors, mentions) are out of scope here — use the raw `blocks` escape hatch.
|
|
112
|
+
*/
|
|
113
|
+
export function markdownToBlocks(md) {
|
|
114
|
+
const lines = md.split('\n');
|
|
115
|
+
const blocks = [];
|
|
116
|
+
let i = 0;
|
|
117
|
+
while (i < lines.length) {
|
|
118
|
+
const line = lines[i].trimEnd();
|
|
119
|
+
const trimmed = line.trim();
|
|
120
|
+
// Fenced code block — consume until closing fence.
|
|
121
|
+
const fence = trimmed.match(/^```(.*)$/);
|
|
122
|
+
if (fence) {
|
|
123
|
+
const lang = fence[1].trim();
|
|
124
|
+
const codeLines = [];
|
|
125
|
+
i++;
|
|
126
|
+
while (i < lines.length && !/^```/.test(lines[i].trim())) {
|
|
127
|
+
codeLines.push(lines[i]);
|
|
128
|
+
i++;
|
|
129
|
+
}
|
|
130
|
+
i++; // skip closing fence
|
|
131
|
+
blocks.push(block(BlockType.Code, {
|
|
132
|
+
elements: [{ text_run: { content: codeLines.join('\n') } }],
|
|
133
|
+
style: { language: codeLanguageCode(lang), wrap: true },
|
|
134
|
+
}));
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (!trimmed) {
|
|
138
|
+
i++;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
// Thematic break.
|
|
142
|
+
if (/^(\*{3,}|-{3,}|_{3,})$/.test(trimmed)) {
|
|
143
|
+
blocks.push({ block_type: BlockType.Divider, divider: {} });
|
|
144
|
+
i++;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
// ATX heading.
|
|
148
|
+
const heading = trimmed.match(/^(#{1,9})\s+(.*)$/);
|
|
149
|
+
if (heading) {
|
|
150
|
+
const bt = headingBlockType(heading[1].length);
|
|
151
|
+
blocks.push(block(bt, { elements: parseInline(heading[2].trim()) }));
|
|
152
|
+
i++;
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
// Task list item (before generic bullet).
|
|
156
|
+
const todo = trimmed.match(/^[-*]\s+\[([ xX])\]\s+(.*)$/);
|
|
157
|
+
if (todo) {
|
|
158
|
+
blocks.push(block(BlockType.Todo, {
|
|
159
|
+
elements: parseInline(todo[2].trim()),
|
|
160
|
+
style: { done: todo[1].toLowerCase() === 'x' },
|
|
161
|
+
}));
|
|
162
|
+
i++;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
// Unordered list item.
|
|
166
|
+
const bullet = trimmed.match(/^[-*]\s+(.*)$/);
|
|
167
|
+
if (bullet) {
|
|
168
|
+
blocks.push(block(BlockType.Bullet, { elements: parseInline(bullet[1].trim()) }));
|
|
169
|
+
i++;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
// Ordered list item.
|
|
173
|
+
const ordered = trimmed.match(/^\d+\.\s+(.*)$/);
|
|
174
|
+
if (ordered) {
|
|
175
|
+
blocks.push(block(BlockType.Ordered, { elements: parseInline(ordered[1].trim()) }));
|
|
176
|
+
i++;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
// Blockquote line.
|
|
180
|
+
const quote = trimmed.match(/^>\s?(.*)$/);
|
|
181
|
+
if (quote) {
|
|
182
|
+
blocks.push(block(BlockType.Quote, { elements: parseInline(quote[1].trim()) }));
|
|
183
|
+
i++;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
// Default: paragraph text.
|
|
187
|
+
blocks.push(block(BlockType.Text, { elements: parseInline(trimmed) }));
|
|
188
|
+
i++;
|
|
189
|
+
}
|
|
190
|
+
return blocks;
|
|
191
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// input: MCP SDK, zod, types (guard/ok/unwrap), lark client (typed v3 + raw request for v2 values)
|
|
2
|
+
// output: registerSheetsTools — feishu_sheets_* tools (电子表格 create/read/write/append/sheet CRUD)
|
|
3
|
+
// pos: Feishu 电子表格 (sheets) spreadsheet authoring & cell I/O for agents
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { guard, ok, unwrap } from './types.js';
|
|
7
|
+
import { resolveDriveUrl, setLinkShare } from './drive.js';
|
|
8
|
+
function sheetsHost() {
|
|
9
|
+
return process.env.FEISHU_DOMAIN === 'lark' ? 'larksuite.com' : 'feishu.cn';
|
|
10
|
+
}
|
|
11
|
+
function sheetUrl(token) {
|
|
12
|
+
return `https://${sheetsHost()}/sheets/${token}`;
|
|
13
|
+
}
|
|
14
|
+
const V2 = (token, suffix) => `/open-apis/sheets/v2/spreadsheets/${token}/${suffix}`;
|
|
15
|
+
export function registerSheetsTools(server, deps) {
|
|
16
|
+
server.tool('feishu_sheets_create', 'Create a new Feishu spreadsheet (电子表格). Returns spreadsheet_token + url. By default link-shared to the tenant (anyone in the org with the link can edit) so a human can open it. Use feishu_sheets_get to list its worksheets, then feishu_sheets_write_range to fill cells.', {
|
|
17
|
+
title: z.string().optional().describe('Spreadsheet title'),
|
|
18
|
+
folder_token: z.string().optional().describe('Drive folder token to create the sheet in (root of the app space if omitted)'),
|
|
19
|
+
share: z.enum(['tenant_edit', 'tenant_view', 'none']).optional().describe('Link-share level (default tenant_edit). none = keep private to the app.'),
|
|
20
|
+
}, async ({ title, folder_token, share }) => guard(deps.client, async (client) => {
|
|
21
|
+
const res = await client.sheets.v3.spreadsheet.create({ data: { title, folder_token } });
|
|
22
|
+
const data = unwrap(res);
|
|
23
|
+
const token = data.spreadsheet?.spreadsheet_token ?? '';
|
|
24
|
+
const level = share ?? 'tenant_edit';
|
|
25
|
+
let shared = false;
|
|
26
|
+
if (level !== 'none') {
|
|
27
|
+
try {
|
|
28
|
+
shared = await setLinkShare(client, token, 'sheet', level);
|
|
29
|
+
}
|
|
30
|
+
catch { /* best-effort */ }
|
|
31
|
+
}
|
|
32
|
+
const url = data.spreadsheet?.url ?? (await resolveDriveUrl(client, token, 'sheet')) ?? sheetUrl(token);
|
|
33
|
+
return ok({ spreadsheet_token: token, title: data.spreadsheet?.title ?? title, url, shared });
|
|
34
|
+
}));
|
|
35
|
+
server.tool('feishu_sheets_get', 'Get a spreadsheet\'s metadata and the list of its worksheets (sheet_id, title, index). You need a sheet_id/title to build A1 ranges like "Sheet1!A1:C10".', {
|
|
36
|
+
spreadsheet_token: z.string().describe('The spreadsheet_token'),
|
|
37
|
+
}, async ({ spreadsheet_token }) => guard(deps.client, async (client) => {
|
|
38
|
+
const metaRes = await client.sheets.v3.spreadsheet.get({ path: { spreadsheet_token } });
|
|
39
|
+
const meta = unwrap(metaRes);
|
|
40
|
+
const sheetsRes = await client.sheets.v3.spreadsheetSheet.query({ path: { spreadsheet_token } });
|
|
41
|
+
const sheetsData = unwrap(sheetsRes);
|
|
42
|
+
return ok({ spreadsheet_token, spreadsheet: meta.spreadsheet ?? null, sheets: sheetsData.sheets ?? [] });
|
|
43
|
+
}));
|
|
44
|
+
server.tool('feishu_sheets_read_range', 'Read cell values from an A1 range (e.g. "Sheet1!A1:C10"). Returns a 2D `values` array.', {
|
|
45
|
+
spreadsheet_token: z.string().describe('The spreadsheet_token'),
|
|
46
|
+
range: z.string().describe('A1-notation range, e.g. "Sheet1!A1:C10"'),
|
|
47
|
+
}, async ({ spreadsheet_token, range }) => guard(deps.client, async (client) => {
|
|
48
|
+
const res = await client.request({
|
|
49
|
+
method: 'GET',
|
|
50
|
+
url: V2(spreadsheet_token, `values/${range}`),
|
|
51
|
+
});
|
|
52
|
+
const data = unwrap(res);
|
|
53
|
+
return ok({ spreadsheet_token, range: data.valueRange?.range ?? range, values: data.valueRange?.values ?? [] });
|
|
54
|
+
}));
|
|
55
|
+
server.tool('feishu_sheets_write_range', 'Write cell values into an A1 range. `values` is a 2D array matching the range shape. Overwrites existing cells.', {
|
|
56
|
+
spreadsheet_token: z.string().describe('The spreadsheet_token'),
|
|
57
|
+
range: z.string().describe('A1-notation range, e.g. "Sheet1!A1:C10"'),
|
|
58
|
+
values: z.array(z.array(z.any())).describe('2D array of cell values (rows of columns)'),
|
|
59
|
+
}, async ({ spreadsheet_token, range, values }) => guard(deps.client, async (client) => {
|
|
60
|
+
const res = await client.request({
|
|
61
|
+
method: 'PUT',
|
|
62
|
+
url: V2(spreadsheet_token, 'values'),
|
|
63
|
+
data: { valueRange: { range, values } },
|
|
64
|
+
});
|
|
65
|
+
const data = unwrap(res);
|
|
66
|
+
return ok({ spreadsheet_token, updatedRange: data.updatedRange, updatedRows: data.updatedRows, updatedCells: data.updatedCells });
|
|
67
|
+
}));
|
|
68
|
+
server.tool('feishu_sheets_append_rows', 'Append rows after the last non-empty row of a range (does not overwrite existing data). `values` is a 2D array of the rows to add.', {
|
|
69
|
+
spreadsheet_token: z.string().describe('The spreadsheet_token'),
|
|
70
|
+
range: z.string().describe('A1-notation range whose sheet/columns the rows are appended to'),
|
|
71
|
+
values: z.array(z.array(z.any())).describe('2D array of rows to append'),
|
|
72
|
+
}, async ({ spreadsheet_token, range, values }) => guard(deps.client, async (client) => {
|
|
73
|
+
const res = await client.request({
|
|
74
|
+
method: 'POST',
|
|
75
|
+
url: V2(spreadsheet_token, 'values_append'),
|
|
76
|
+
data: { valueRange: { range, values } },
|
|
77
|
+
});
|
|
78
|
+
const data = unwrap(res);
|
|
79
|
+
return ok({ spreadsheet_token, appended: data.updates ?? null });
|
|
80
|
+
}));
|
|
81
|
+
server.tool('feishu_sheets_add_sheet', 'Add a new worksheet (tab) to a spreadsheet. Returns the batch-update replies (including the new sheetId).', {
|
|
82
|
+
spreadsheet_token: z.string().describe('The spreadsheet_token'),
|
|
83
|
+
title: z.string().describe('Title for the new worksheet'),
|
|
84
|
+
index: z.number().int().min(0).optional().describe('0-based tab position (appended to the end if omitted)'),
|
|
85
|
+
}, async ({ spreadsheet_token, title, index }) => guard(deps.client, async (client) => {
|
|
86
|
+
const properties = { title };
|
|
87
|
+
if (index != null)
|
|
88
|
+
properties.index = index;
|
|
89
|
+
const res = await client.request({
|
|
90
|
+
method: 'POST',
|
|
91
|
+
url: V2(spreadsheet_token, 'sheets_batch_update'),
|
|
92
|
+
data: { requests: [{ addSheet: { properties } }] },
|
|
93
|
+
});
|
|
94
|
+
const data = unwrap(res);
|
|
95
|
+
return ok({ spreadsheet_token, replies: data.replies ?? [] });
|
|
96
|
+
}));
|
|
97
|
+
server.tool('feishu_sheets_delete_sheet', 'Delete a worksheet (tab) from a spreadsheet by sheet_id. Irreversible. Find sheet_id with feishu_sheets_get.', {
|
|
98
|
+
spreadsheet_token: z.string().describe('The spreadsheet_token'),
|
|
99
|
+
sheet_id: z.string().describe('The worksheet sheet_id to delete'),
|
|
100
|
+
}, async ({ spreadsheet_token, sheet_id }) => guard(deps.client, async (client) => {
|
|
101
|
+
const res = await client.request({
|
|
102
|
+
method: 'POST',
|
|
103
|
+
url: V2(spreadsheet_token, 'sheets_batch_update'),
|
|
104
|
+
data: { requests: [{ deleteSheet: { sheetId: sheet_id } }] },
|
|
105
|
+
});
|
|
106
|
+
const data = unwrap(res);
|
|
107
|
+
return ok({ spreadsheet_token, sheet_id, deleted: true, replies: data.replies ?? [] });
|
|
108
|
+
}));
|
|
109
|
+
server.tool('feishu_sheets_delete', 'Delete (trash) an ENTIRE spreadsheet — the whole file, not a worksheet. Moves it to the drive recycle bin (recoverable there). Use feishu_sheets_delete_sheet to drop a single worksheet instead. Requires the user to own the file (or have manage rights).', {
|
|
110
|
+
spreadsheet_token: z.string().describe('The spreadsheet_token of the file to delete'),
|
|
111
|
+
}, async ({ spreadsheet_token }) => guard(deps.client, async (client) => {
|
|
112
|
+
const res = await client.drive.v1.file.delete({
|
|
113
|
+
path: { file_token: spreadsheet_token },
|
|
114
|
+
params: { type: 'sheet' },
|
|
115
|
+
});
|
|
116
|
+
unwrap(res);
|
|
117
|
+
return ok({ spreadsheet_token, deleted: true });
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { LarkClient } from './client.js';
|
|
2
|
+
/** Dependencies injected into each register*Tools function (client is mockable in tests). */
|
|
3
|
+
export interface FeishuToolDeps {
|
|
4
|
+
client: LarkClient | null;
|
|
5
|
+
}
|
|
6
|
+
export interface McpResult {
|
|
7
|
+
content: Array<{
|
|
8
|
+
type: 'text';
|
|
9
|
+
text: string;
|
|
10
|
+
}>;
|
|
11
|
+
isError?: boolean;
|
|
12
|
+
[key: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
/** Wrap a successful payload as an MCP text result (JSON-encoded). */
|
|
15
|
+
export declare function ok(data: unknown): McpResult;
|
|
16
|
+
/** Wrap an error message as an MCP error result. */
|
|
17
|
+
export declare function fail(message: string): McpResult;
|
|
18
|
+
/** Standard message when the server has no Feishu credentials configured. */
|
|
19
|
+
export declare const NO_CLIENT_MESSAGE: string;
|
|
20
|
+
/**
|
|
21
|
+
* Unwrap a lark SDK response. The SDK resolves with `{ code, msg, data }`;
|
|
22
|
+
* a non-zero `code` is an API-level error that must surface to the agent.
|
|
23
|
+
*/
|
|
24
|
+
export declare function unwrap<T = unknown>(res: unknown): T;
|
|
25
|
+
/** Run a tool body with uniform client-presence + error handling. */
|
|
26
|
+
export declare function guard(client: LarkClient | null, body: (client: LarkClient) => Promise<McpResult>): Promise<McpResult>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// input: LarkClient type
|
|
2
|
+
// output: FeishuToolDeps + MCP result helpers (ok/fail) + lark response unwrap
|
|
3
|
+
// pos: Shared plumbing for feishu_* tool registration modules
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
/** Wrap a successful payload as an MCP text result (JSON-encoded). */
|
|
6
|
+
export function ok(data) {
|
|
7
|
+
const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
|
|
8
|
+
return { content: [{ type: 'text', text }] };
|
|
9
|
+
}
|
|
10
|
+
/** Wrap an error message as an MCP error result. */
|
|
11
|
+
export function fail(message) {
|
|
12
|
+
return { content: [{ type: 'text', text: message }], isError: true };
|
|
13
|
+
}
|
|
14
|
+
/** Standard message when the server has no Feishu credentials configured. */
|
|
15
|
+
export const NO_CLIENT_MESSAGE = 'Feishu is not configured (missing FEISHU_APP_ID / FEISHU_APP_SECRET). ' +
|
|
16
|
+
'Set them in the Cortex config and restart, and grant the app docx/drive/wiki/bitable/sheets scopes.';
|
|
17
|
+
/**
|
|
18
|
+
* Unwrap a lark SDK response. The SDK resolves with `{ code, msg, data }`;
|
|
19
|
+
* a non-zero `code` is an API-level error that must surface to the agent.
|
|
20
|
+
*/
|
|
21
|
+
export function unwrap(res) {
|
|
22
|
+
const r = res;
|
|
23
|
+
if (r && typeof r.code === 'number' && r.code !== 0) {
|
|
24
|
+
throw new Error(`Feishu API error ${r.code}: ${r.msg ?? 'unknown'}`);
|
|
25
|
+
}
|
|
26
|
+
return (r?.data ?? r);
|
|
27
|
+
}
|
|
28
|
+
/** Run a tool body with uniform client-presence + error handling. */
|
|
29
|
+
export async function guard(client, body) {
|
|
30
|
+
if (!client)
|
|
31
|
+
return fail(NO_CLIENT_MESSAGE);
|
|
32
|
+
try {
|
|
33
|
+
return await body(client);
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
return fail(`Feishu operation failed: ${e.message}`);
|
|
37
|
+
}
|
|
38
|
+
}
|