create-deepagent-server 0.0.0-stage → 0.2.0

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.
Files changed (204) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +292 -2
  3. package/bin/create-deepagent-server.js +27 -0
  4. package/package.json +50 -4
  5. package/src/args.js +195 -0
  6. package/src/cli.js +269 -0
  7. package/src/dependencies.js +34 -0
  8. package/src/prompts.js +86 -0
  9. package/src/registry.js +68 -0
  10. package/src/scaffold.js +181 -0
  11. package/src/setup.js +79 -0
  12. package/src/ui.js +43 -0
  13. package/src/version.js +1 -0
  14. package/src/versions.js +29 -0
  15. package/templates/deepagent/js/deployment/Dockerfile +19 -0
  16. package/templates/deepagent/js/scripts/check.js +97 -0
  17. package/templates/deepagent/js/scripts/dev.js +40 -0
  18. package/templates/deepagent/js/src/agents/factory.js +11 -0
  19. package/templates/deepagent/js/src/agents/index.js +4 -0
  20. package/templates/deepagent/js/src/agents/prompts/index.js +2 -0
  21. package/templates/deepagent/js/src/agents/prompts/loader.js +53 -0
  22. package/templates/deepagent/js/src/agents/prompts/subagents/analyst.md +17 -0
  23. package/templates/deepagent/js/src/agents/prompts/subagents/coder.md +17 -0
  24. package/templates/deepagent/js/src/agents/prompts/supervisor.js +21 -0
  25. package/templates/deepagent/js/src/agents/prompts/supervisor.md +41 -0
  26. package/templates/deepagent/js/src/agents/state/index.js +1 -0
  27. package/templates/deepagent/js/src/agents/state/types.js +11 -0
  28. package/templates/deepagent/js/src/agents/subagents/analyst.js +12 -0
  29. package/templates/deepagent/js/src/agents/subagents/coder.js +12 -0
  30. package/templates/deepagent/js/src/agents/subagents/index.js +9 -0
  31. package/templates/deepagent/js/src/agents/supervisor.js +64 -0
  32. package/templates/deepagent/js/src/api/app.js +29 -0
  33. package/templates/deepagent/js/src/api/middleware/auth.js +36 -0
  34. package/templates/deepagent/js/src/api/middleware/error.js +30 -0
  35. package/templates/deepagent/js/src/api/routes/agent.js +43 -0
  36. package/templates/deepagent/js/src/api/routes/health.js +40 -0
  37. package/templates/deepagent/js/src/api/routes/session.js +42 -0
  38. package/templates/deepagent/js/src/app.js +98 -0
  39. package/templates/deepagent/js/src/backends/composite.js +22 -0
  40. package/templates/deepagent/js/src/backends/filesystem.js +9 -0
  41. package/templates/deepagent/js/src/backends/index.js +60 -0
  42. package/templates/deepagent/js/src/backends/sandbox.js +26 -0
  43. package/templates/deepagent/js/src/config/agent.js +14 -0
  44. package/templates/deepagent/js/src/config/database.js +19 -0
  45. package/templates/deepagent/js/src/config/env.js +96 -0
  46. package/templates/deepagent/js/src/config/index.js +45 -0
  47. package/templates/deepagent/js/src/graph/checkpointer.js +28 -0
  48. package/templates/deepagent/js/src/graph/compile.js +9 -0
  49. package/templates/deepagent/js/src/graph/index.js +3 -0
  50. package/templates/deepagent/js/src/graph/store.js +28 -0
  51. package/templates/deepagent/js/src/index.js +39 -0
  52. package/templates/deepagent/js/src/memory/index.js +8 -0
  53. package/templates/deepagent/js/src/memory/manager.js +50 -0
  54. package/templates/deepagent/js/src/memory/store.js +43 -0
  55. package/templates/deepagent/js/src/middleware/approval.js +47 -0
  56. package/templates/deepagent/js/src/middleware/context.js +35 -0
  57. package/templates/deepagent/js/src/middleware/index.js +9 -0
  58. package/templates/deepagent/js/src/middleware/logging.js +70 -0
  59. package/templates/deepagent/js/src/middleware/security.js +58 -0
  60. package/templates/deepagent/js/src/model/config.js +38 -0
  61. package/templates/deepagent/js/src/model/index.js +9 -0
  62. package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
  63. package/templates/deepagent/js/src/model/presets.js +71 -0
  64. package/templates/deepagent/js/src/sandbox/config.js +12 -0
  65. package/templates/deepagent/js/src/sandbox/index.js +3 -0
  66. package/templates/deepagent/js/src/sandbox/manager.js +161 -0
  67. package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
  68. package/templates/deepagent/js/src/schemas/agent.js +40 -0
  69. package/templates/deepagent/js/src/schemas/common.js +24 -0
  70. package/templates/deepagent/js/src/schemas/locale.js +4 -0
  71. package/templates/deepagent/js/src/schemas/session.js +27 -0
  72. package/templates/deepagent/js/src/services/agent.js +136 -0
  73. package/templates/deepagent/js/src/services/memory.js +33 -0
  74. package/templates/deepagent/js/src/services/session.js +118 -0
  75. package/templates/deepagent/js/src/skills/index.js +21 -0
  76. package/templates/deepagent/js/src/skills/loader.js +75 -0
  77. package/templates/deepagent/js/src/storage/database/client.js +57 -0
  78. package/templates/deepagent/js/src/storage/database/migrations/001_init.sql +20 -0
  79. package/templates/deepagent/js/src/storage/logger/index.js +21 -0
  80. package/templates/deepagent/js/src/storage/redis/client.js +51 -0
  81. package/templates/deepagent/js/src/storage/shutdown/index.js +58 -0
  82. package/templates/deepagent/js/src/tools/database/index.js +1 -0
  83. package/templates/deepagent/js/src/tools/database/query.js +74 -0
  84. package/templates/deepagent/js/src/tools/filesystem/index.js +102 -0
  85. package/templates/deepagent/js/src/tools/index.js +25 -0
  86. package/templates/deepagent/js/src/tools/mcp/client.js +42 -0
  87. package/templates/deepagent/js/src/tools/mcp/connections.js +64 -0
  88. package/templates/deepagent/js/src/tools/mcp/index.js +10 -0
  89. package/templates/deepagent/js/src/tools/mcp/registry.js +36 -0
  90. package/templates/deepagent/js/src/utils/errors.js +73 -0
  91. package/templates/deepagent/js/src/utils/helpers.js +57 -0
  92. package/templates/deepagent/js/src/utils/validation.js +15 -0
  93. package/templates/deepagent/js/tests/agents/prompts.test.js +30 -0
  94. package/templates/deepagent/js/tests/agents/supervisor.test.js +42 -0
  95. package/templates/deepagent/js/tests/config/database.test.js +40 -0
  96. package/templates/deepagent/js/tests/integration/api.test.js +114 -0
  97. package/templates/deepagent/js/tests/middleware/security.test.js +27 -0
  98. package/templates/deepagent/js/tests/model/config.test.js +61 -0
  99. package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
  100. package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
  101. package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
  102. package/templates/deepagent/js/tests/services/session.test.js +41 -0
  103. package/templates/deepagent/js/tests/tools/query.test.js +27 -0
  104. package/templates/deepagent/shared/README.md +249 -0
  105. package/templates/deepagent/shared/_editorconfig +12 -0
  106. package/templates/deepagent/shared/_env.example +86 -0
  107. package/templates/deepagent/shared/_gitignore +22 -0
  108. package/templates/deepagent/shared/deployment/docker-compose.yml +60 -0
  109. package/templates/deepagent/shared/resources/AGENTS.md +32 -0
  110. package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
  111. package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
  112. package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
  113. package/templates/deepagent/shared/workspaces/README.md +5 -0
  114. package/templates/deepagent/ts/deployment/Dockerfile +25 -0
  115. package/templates/deepagent/ts/scripts/check.ts +99 -0
  116. package/templates/deepagent/ts/scripts/copy-assets.ts +37 -0
  117. package/templates/deepagent/ts/scripts/dev.ts +40 -0
  118. package/templates/deepagent/ts/src/agents/factory.ts +11 -0
  119. package/templates/deepagent/ts/src/agents/index.ts +4 -0
  120. package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
  121. package/templates/deepagent/ts/src/agents/prompts/loader.ts +53 -0
  122. package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
  123. package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
  124. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +41 -0
  125. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
  126. package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
  127. package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
  128. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +18 -0
  129. package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
  130. package/templates/deepagent/ts/src/agents/subagents/index.ts +9 -0
  131. package/templates/deepagent/ts/src/agents/supervisor.ts +82 -0
  132. package/templates/deepagent/ts/src/api/app.ts +48 -0
  133. package/templates/deepagent/ts/src/api/middleware/auth.ts +38 -0
  134. package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
  135. package/templates/deepagent/ts/src/api/routes/agent.ts +48 -0
  136. package/templates/deepagent/ts/src/api/routes/health.ts +47 -0
  137. package/templates/deepagent/ts/src/api/routes/session.ts +47 -0
  138. package/templates/deepagent/ts/src/app.ts +111 -0
  139. package/templates/deepagent/ts/src/backends/composite.ts +34 -0
  140. package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
  141. package/templates/deepagent/ts/src/backends/index.ts +76 -0
  142. package/templates/deepagent/ts/src/backends/sandbox.ts +33 -0
  143. package/templates/deepagent/ts/src/config/agent.ts +37 -0
  144. package/templates/deepagent/ts/src/config/database.ts +21 -0
  145. package/templates/deepagent/ts/src/config/env.ts +106 -0
  146. package/templates/deepagent/ts/src/config/index.ts +84 -0
  147. package/templates/deepagent/ts/src/graph/checkpointer.ts +29 -0
  148. package/templates/deepagent/ts/src/graph/compile.ts +15 -0
  149. package/templates/deepagent/ts/src/graph/index.ts +3 -0
  150. package/templates/deepagent/ts/src/graph/store.ts +29 -0
  151. package/templates/deepagent/ts/src/index.ts +39 -0
  152. package/templates/deepagent/ts/src/memory/index.ts +11 -0
  153. package/templates/deepagent/ts/src/memory/manager.ts +76 -0
  154. package/templates/deepagent/ts/src/memory/store.ts +59 -0
  155. package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
  156. package/templates/deepagent/ts/src/middleware/context.ts +37 -0
  157. package/templates/deepagent/ts/src/middleware/index.ts +9 -0
  158. package/templates/deepagent/ts/src/middleware/logging.ts +71 -0
  159. package/templates/deepagent/ts/src/middleware/security.ts +61 -0
  160. package/templates/deepagent/ts/src/model/config.ts +56 -0
  161. package/templates/deepagent/ts/src/model/index.ts +14 -0
  162. package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
  163. package/templates/deepagent/ts/src/model/presets.ts +82 -0
  164. package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
  165. package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
  166. package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
  167. package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
  168. package/templates/deepagent/ts/src/schemas/agent.ts +48 -0
  169. package/templates/deepagent/ts/src/schemas/common.ts +26 -0
  170. package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
  171. package/templates/deepagent/ts/src/schemas/session.ts +31 -0
  172. package/templates/deepagent/ts/src/services/agent.ts +170 -0
  173. package/templates/deepagent/ts/src/services/memory.ts +43 -0
  174. package/templates/deepagent/ts/src/services/session.ts +158 -0
  175. package/templates/deepagent/ts/src/skills/index.ts +26 -0
  176. package/templates/deepagent/ts/src/skills/loader.ts +90 -0
  177. package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
  178. package/templates/deepagent/ts/src/storage/database/migrations/001_init.sql +20 -0
  179. package/templates/deepagent/ts/src/storage/logger/index.ts +25 -0
  180. package/templates/deepagent/ts/src/storage/redis/client.ts +57 -0
  181. package/templates/deepagent/ts/src/storage/shutdown/index.ts +82 -0
  182. package/templates/deepagent/ts/src/tools/database/index.ts +5 -0
  183. package/templates/deepagent/ts/src/tools/database/query.ts +79 -0
  184. package/templates/deepagent/ts/src/tools/filesystem/index.ts +110 -0
  185. package/templates/deepagent/ts/src/tools/index.ts +43 -0
  186. package/templates/deepagent/ts/src/tools/mcp/client.ts +54 -0
  187. package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
  188. package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
  189. package/templates/deepagent/ts/src/tools/mcp/registry.ts +45 -0
  190. package/templates/deepagent/ts/src/utils/errors.ts +95 -0
  191. package/templates/deepagent/ts/src/utils/helpers.ts +57 -0
  192. package/templates/deepagent/ts/src/utils/validation.ts +17 -0
  193. package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
  194. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
  195. package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
  196. package/templates/deepagent/ts/tests/integration/api.test.ts +122 -0
  197. package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
  198. package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
  199. package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
  200. package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
  201. package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
  202. package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
  203. package/templates/deepagent/ts/tests/tools/query.test.ts +27 -0
  204. package/templates/deepagent/ts/tsconfig.json +19 -0
@@ -0,0 +1,25 @@
1
+ import pino, { type Logger } from "pino";
2
+
3
+ import type { AppConfig } from "../../config/index.js";
4
+
5
+ export type { Logger };
6
+
7
+ /** `LOG_PRETTY=true` 时使用的 pino-pretty 传输配置。 */
8
+ const PRETTY_TRANSPORT = {
9
+ transport: {
10
+ target: "pino-pretty",
11
+ options: {
12
+ colorize: true,
13
+ translateTime: "SYS:standard",
14
+ ignore: "pid,hostname",
15
+ },
16
+ },
17
+ };
18
+
19
+ export const createLogger = (config: Pick<AppConfig, "env" | "logging">): Logger => {
20
+ return pino({
21
+ level: config.logging.level,
22
+ base: { service: "deepagent", env: config.env.NODE_ENV },
23
+ ...(config.logging.pretty ? PRETTY_TRANSPORT : {}),
24
+ });
25
+ };
@@ -0,0 +1,57 @@
1
+ import { performance } from "node:perf_hooks";
2
+
3
+ import { Redis } from "ioredis";
4
+
5
+ import { ConfigurationError } from "../../utils/errors.js";
6
+ import { errorMessage } from "../../utils/helpers.js";
7
+
8
+ let client: Redis | undefined;
9
+
10
+ /** 懒加载共享的 Redis 客户端(首次执行命令时才建立连接)。 */
11
+ export const getRedis = (url = process.env.REDIS_URL): Redis => {
12
+ if (!url) {
13
+ throw new ConfigurationError("未配置 REDIS_URL。请先在 .env 中设置后再使用 Redis 功能。");
14
+ }
15
+
16
+ client ??= new Redis(url, {
17
+ lazyConnect: true,
18
+ maxRetriesPerRequest: 1,
19
+ enableOfflineQueue: false,
20
+ });
21
+
22
+ return client;
23
+ };
24
+
25
+ export interface RedisHealth {
26
+ ok: boolean;
27
+ latencyMs?: number;
28
+ error?: string;
29
+ }
30
+
31
+ const probe = async (): Promise<RedisHealth> => {
32
+ const redis = getRedis();
33
+ if (redis.status === "wait") await redis.connect();
34
+
35
+ const startedAt = performance.now();
36
+ await redis.ping();
37
+
38
+ return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
39
+ };
40
+
41
+ /** 健康检查只返回状态,不向上抛错:连接或 ping 失败都折算成 `ok: false`。 */
42
+ export const checkRedis = async (): Promise<RedisHealth> => {
43
+ if (!process.env.REDIS_URL) {
44
+ return { ok: false, error: "未配置 REDIS_URL" };
45
+ }
46
+
47
+ return probe().catch((error: unknown) => ({ ok: false, error: errorMessage(error) }));
48
+ };
49
+
50
+ export const closeRedis = async (): Promise<void> => {
51
+ if (!client) return;
52
+
53
+ const current = client;
54
+ client = undefined;
55
+
56
+ await current.quit().catch(() => current.disconnect());
57
+ };
@@ -0,0 +1,82 @@
1
+ import type { Logger } from "../logger/index.js";
2
+ import { errorMessage } from "../../utils/helpers.js";
3
+
4
+ export interface ShutdownHook {
5
+ name: string;
6
+ close: () => Promise<void> | void;
7
+ }
8
+
9
+ export interface ShutdownManager {
10
+ /** 注册一个随进程关闭而关闭的资源,返回取消注册函数。 */
11
+ register: (hook: ShutdownHook) => () => void;
12
+ /** 关闭所有已注册资源,只执行一次;多个信号并发调用也安全。 */
13
+ shutdown: (reason?: string) => Promise<void>;
14
+ /** 安装 SIGINT / SIGTERM 处理器。 */
15
+ install: () => void;
16
+ }
17
+
18
+ export interface ShutdownOptions {
19
+ logger: Logger;
20
+ timeoutMs?: number;
21
+ }
22
+
23
+ const withTimeout = (promise: Promise<void>, timeoutMs: number): Promise<void> => {
24
+ let timer: NodeJS.Timeout | undefined;
25
+
26
+ const timeout = new Promise<never>((_, reject) => {
27
+ timer = setTimeout(() => reject(new Error(`hook 执行超时(${timeoutMs}ms)`)), timeoutMs);
28
+ });
29
+
30
+ return Promise.race([promise, timeout]).finally(() => {
31
+ if (timer) clearTimeout(timer);
32
+ });
33
+ };
34
+
35
+ export const createShutdownManager = ({
36
+ logger,
37
+ timeoutMs = 10_000,
38
+ }: ShutdownOptions): ShutdownManager => {
39
+ const hooks: ShutdownHook[] = [];
40
+ let pending: Promise<void> | undefined;
41
+
42
+ const closeHook = (hook: ShutdownHook): Promise<void> => {
43
+ return withTimeout(Promise.resolve(hook.close()), timeoutMs).then(
44
+ () => logger.info({ hook: hook.name }, "已关闭"),
45
+ (error: unknown) =>
46
+ logger.warn({ hook: hook.name, error: errorMessage(error) }, "关闭资源失败"),
47
+ );
48
+ };
49
+
50
+ const run = async (reason: string): Promise<void> => {
51
+ logger.info({ reason, hooks: hooks.map((hook) => hook.name) }, "开始关闭");
52
+
53
+ await Promise.all(hooks.map(closeHook));
54
+
55
+ logger.info("关闭完成");
56
+ };
57
+
58
+ const manager: ShutdownManager = {
59
+ register: (hook) => {
60
+ hooks.push(hook);
61
+ return () => {
62
+ const index = hooks.findIndex((item) => item === hook);
63
+ if (index >= 0) hooks.splice(index, 1);
64
+ };
65
+ },
66
+
67
+ shutdown: (reason = "shutdown") => {
68
+ pending ??= run(reason);
69
+ return pending;
70
+ },
71
+
72
+ install: () => {
73
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
74
+ process.once(signal, () => {
75
+ void manager.shutdown(signal).finally(() => process.exit(0));
76
+ });
77
+ }
78
+ },
79
+ };
80
+
81
+ return manager;
82
+ };
@@ -0,0 +1,5 @@
1
+ export {
2
+ assertReadOnlyQuery,
3
+ createQueryDatabaseTool,
4
+ type QueryDatabaseToolOptions,
5
+ } from "./query.js";
@@ -0,0 +1,79 @@
1
+ import { tool } from "@langchain/core/tools";
2
+ import { z } from "zod";
3
+
4
+ import { getPool } from "../../storage/database/client.js";
5
+
6
+ const READ_ONLY_START = /^\s*(?:select|with)\b/i;
7
+ const FORBIDDEN_KEYWORDS =
8
+ /\b(insert|update|delete|drop|alter|truncate|create|grant|revoke|copy|vacuum|reindex|call|do)\b/i;
9
+
10
+ /**
11
+ * 对模型生成的 SQL 做前置校验。查询同时运行在 READ ONLY 事务中,
12
+ * 即使绕过校验也无法修改数据。
13
+ */
14
+ export const assertReadOnlyQuery = (sql: string): void => {
15
+ const statement = sql.trim().replace(/;\s*$/, "");
16
+
17
+ if (!READ_ONLY_START.test(statement)) {
18
+ throw new Error("只允许 SELECT 和 WITH 查询。");
19
+ }
20
+ if (statement.includes(";")) {
21
+ throw new Error("只允许单条 SQL 语句。");
22
+ }
23
+ if (FORBIDDEN_KEYWORDS.test(statement)) {
24
+ throw new Error("查询包含写入或 DDL 关键字,已拒绝执行。");
25
+ }
26
+ };
27
+
28
+ const querySchema = z.object({
29
+ sql: z.string().min(1).describe("单条只读 SQL 语句(SELECT 或 WITH)。"),
30
+ params: z
31
+ .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))
32
+ .default([])
33
+ .describe("与 $1、$2…… 占位符对应的位置参数。"),
34
+ limit: z.number().int().min(1).max(500).default(100),
35
+ });
36
+
37
+ export interface QueryDatabaseToolOptions {
38
+ /** 未提供时回退到 DATABASE_URL 环境变量。 */
39
+ connectionString?: string;
40
+ }
41
+
42
+ /** 只读、参数化的 PostgreSQL 查询工具。 */
43
+ export const createQueryDatabaseTool = ({ connectionString }: QueryDatabaseToolOptions = {}) => {
44
+ return tool(
45
+ async ({ sql, params, limit }: z.infer<typeof querySchema>) => {
46
+ assertReadOnlyQuery(sql);
47
+
48
+ const client = await getPool(connectionString).connect();
49
+
50
+ try {
51
+ await client.query("BEGIN TRANSACTION READ ONLY");
52
+ await client.query("SET LOCAL statement_timeout = '10s'");
53
+
54
+ const result = await client.query(sql, params);
55
+ await client.query("COMMIT");
56
+
57
+ return JSON.stringify(
58
+ {
59
+ rowCount: result.rowCount,
60
+ truncated: result.rows.length > limit,
61
+ rows: result.rows.slice(0, limit),
62
+ },
63
+ null,
64
+ 2,
65
+ );
66
+ } catch (error) {
67
+ await client.query("ROLLBACK").catch(() => undefined);
68
+ throw error;
69
+ } finally {
70
+ client.release();
71
+ }
72
+ },
73
+ {
74
+ name: "query_database",
75
+ description: "对应用 PostgreSQL 执行单条只读 SQL,并以 JSON 返回结果行。",
76
+ schema: querySchema,
77
+ },
78
+ );
79
+ };
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs/promises";
2
+ import nodePath from "node:path";
3
+
4
+ import { tool } from "@langchain/core/tools";
5
+ import { z } from "zod";
6
+
7
+ export interface WorkspaceToolsOptions {
8
+ rootDir: string;
9
+ maxReadBytes?: number;
10
+ }
11
+
12
+ const resolveInsideRoot = (rootDir: string, target: string): string => {
13
+ const root = nodePath.resolve(rootDir);
14
+ const resolved = nodePath.resolve(root, target);
15
+
16
+ if (resolved !== root && !resolved.startsWith(`${root}${nodePath.sep}`)) {
17
+ throw new Error(`路径越出了工作区根目录:${target}`);
18
+ }
19
+
20
+ return resolved;
21
+ };
22
+
23
+ /**
24
+ * 面向应用自有文件的额外工作区工具。Deep Agents 已内置对后端的
25
+ * read_file/write_file/edit_file;这些工具限定在 `workspaces/` 内,
26
+ * 方便服务层(而不是模型)安全地读取产物。
27
+ */
28
+ export const createWorkspaceTools = ({
29
+ rootDir,
30
+ maxReadBytes = 200_000,
31
+ }: WorkspaceToolsOptions) => {
32
+ const readSchema = z.object({
33
+ filePath: z.string().min(1).describe("相对于工作区根目录的路径。"),
34
+ maxBytes: z.number().int().positive().default(maxReadBytes),
35
+ });
36
+
37
+ const readFile = tool(
38
+ async ({ filePath, maxBytes }: z.infer<typeof readSchema>) => {
39
+ const resolved = resolveInsideRoot(rootDir, filePath);
40
+ const content = await fs.readFile(resolved, "utf8");
41
+ if (content.length <= maxBytes) return content;
42
+
43
+ return `${content.slice(0, maxBytes)}\n… 已在 ${maxBytes} 个字符处截断`;
44
+ },
45
+ {
46
+ name: "read_workspace_file",
47
+ description: "按相对于工作区根目录的路径读取 Agent 工作区中的文件。",
48
+ schema: readSchema,
49
+ },
50
+ );
51
+
52
+ const writeSchema = z.object({
53
+ filePath: z.string().min(1),
54
+ content: z.string(),
55
+ append: z.boolean().default(false),
56
+ });
57
+
58
+ const writeFile = tool(
59
+ async ({ filePath, content, append }: z.infer<typeof writeSchema>) => {
60
+ const resolved = resolveInsideRoot(rootDir, filePath);
61
+ await fs.mkdir(nodePath.dirname(resolved), { recursive: true });
62
+
63
+ if (append) {
64
+ await fs.appendFile(resolved, content, "utf8");
65
+ } else {
66
+ await fs.writeFile(resolved, content, "utf8");
67
+ }
68
+
69
+ return `已写入 ${content.length} 个字符到 ${filePath}`;
70
+ },
71
+ {
72
+ name: "write_workspace_file",
73
+ description: "在 Agent 工作区中创建或覆盖文件,也可以选择追加内容。",
74
+ schema: writeSchema,
75
+ },
76
+ );
77
+
78
+ const listSchema = z.object({
79
+ directory: z.string().default("."),
80
+ recursive: z.boolean().default(false),
81
+ });
82
+
83
+ const listFiles = tool(
84
+ async ({ directory, recursive }: z.infer<typeof listSchema>) => {
85
+ const resolved = resolveInsideRoot(rootDir, directory);
86
+ const entries = await fs.readdir(resolved, {
87
+ recursive,
88
+ withFileTypes: true,
89
+ });
90
+
91
+ const files = entries
92
+ .map((entry) => ({
93
+ name: entry.name,
94
+ path: nodePath.relative(rootDir, nodePath.join(entry.parentPath, entry.name)),
95
+ type: entry.isDirectory() ? "目录" : "文件",
96
+ }))
97
+ .sort((a, b) => a.path.localeCompare(b.path))
98
+ .slice(0, 500);
99
+
100
+ return JSON.stringify({ root: directory, files }, null, 2);
101
+ },
102
+ {
103
+ name: "list_workspace_files",
104
+ description: "列出 Agent 工作区中的文件和目录,不读取文件内容。",
105
+ schema: listSchema,
106
+ },
107
+ );
108
+
109
+ return [readFile, writeFile, listFiles];
110
+ };
@@ -0,0 +1,43 @@
1
+ import type { StructuredToolInterface } from "@langchain/core/tools";
2
+
3
+ import { createQueryDatabaseTool } from "./database/index.js";
4
+ import { createWorkspaceTools } from "./filesystem/index.js";
5
+
6
+ export {
7
+ assertReadOnlyQuery,
8
+ createQueryDatabaseTool,
9
+ type QueryDatabaseToolOptions,
10
+ } from "./database/index.js";
11
+ export { createWorkspaceTools } from "./filesystem/index.js";
12
+ export {
13
+ createMcpAdapter,
14
+ createMcpToolRegistry,
15
+ loadMcpConnections,
16
+ loadMcpTools,
17
+ McpToolRegistry,
18
+ mcpServerSchema,
19
+ type McpServerConnection,
20
+ } from "./mcp/index.js";
21
+
22
+ export interface DefaultToolsOptions {
23
+ workspaceRoot: string;
24
+ /** 配置后启用只读 SQL 工具;未配置时不注册。 */
25
+ databaseUrl?: string;
26
+ additionalTools?: StructuredToolInterface[];
27
+ }
28
+
29
+ /**
30
+ * 主 Agent 和子 Agent 可用的工具,位于 Deep Agents 内置工具
31
+ * (write_todos、read_file、write_file、task 等)之上。
32
+ */
33
+ export const createDefaultTools = ({
34
+ workspaceRoot,
35
+ databaseUrl,
36
+ additionalTools = [],
37
+ }: DefaultToolsOptions): StructuredToolInterface[] => {
38
+ return [
39
+ ...(databaseUrl ? [createQueryDatabaseTool({ connectionString: databaseUrl })] : []),
40
+ ...createWorkspaceTools({ rootDir: workspaceRoot }),
41
+ ...additionalTools,
42
+ ];
43
+ };
@@ -0,0 +1,54 @@
1
+ import type { DynamicStructuredTool } from "@langchain/core/tools";
2
+ import { MCPAdapter, type MCPAdapterConfig } from "@langchain/mcp-adapters";
3
+
4
+ import type { McpServerConnection } from "./connections.js";
5
+
6
+ type AdapterServers = NonNullable<MCPAdapterConfig["servers"]>;
7
+
8
+ const toAdapterServers = (connections: Record<string, McpServerConnection>): AdapterServers => {
9
+ const servers: AdapterServers = {};
10
+
11
+ for (const [name, connection] of Object.entries(connections)) {
12
+ if (connection.transport === "stdio") {
13
+ servers[name] = {
14
+ transport: "stdio",
15
+ command: connection.command,
16
+ args: connection.args,
17
+ env: connection.env,
18
+ };
19
+ } else if (connection.transport === "http") {
20
+ servers[name] = { transport: "http", url: connection.url };
21
+ } else {
22
+ servers[name] = { transport: "sse", url: connection.url };
23
+ }
24
+ }
25
+
26
+ return servers;
27
+ };
28
+
29
+ /** 创建多服务器 MCP 适配器;连接按需建立。 */
30
+ export const createMcpAdapter = (connections: Record<string, McpServerConnection>): MCPAdapter => {
31
+ return new MCPAdapter({
32
+ servers: toAdapterServers(connections),
33
+ onConnectionError: "ignore",
34
+ });
35
+ };
36
+
37
+ export interface LoadedMcpTools {
38
+ adapter: MCPAdapter | null;
39
+ tools: DynamicStructuredTool[];
40
+ }
41
+
42
+ /** 加载已配置的 MCP 服务器暴露的全部工具。 */
43
+ export const loadMcpTools = async (
44
+ connections: Record<string, McpServerConnection>,
45
+ ): Promise<LoadedMcpTools> => {
46
+ if (Object.keys(connections).length === 0) {
47
+ return { adapter: null, tools: [] };
48
+ }
49
+
50
+ const adapter = createMcpAdapter(connections);
51
+ const tools = await adapter.listTools();
52
+
53
+ return { adapter, tools };
54
+ };
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
2
+
3
+ import { ConfigurationError } from "../../utils/errors.js";
4
+ import { errorMessage } from "../../utils/helpers.js";
5
+
6
+ const stdioConnectionSchema = z.object({
7
+ transport: z.literal("stdio"),
8
+ command: z.string().min(1),
9
+ args: z.array(z.string()).default([]),
10
+ env: z.record(z.string(), z.string()).default({}),
11
+ });
12
+
13
+ const httpConnectionSchema = z.object({
14
+ transport: z.literal("http"),
15
+ url: z.string().min(1),
16
+ headers: z.record(z.string(), z.string()).default({}),
17
+ });
18
+
19
+ const sseConnectionSchema = z.object({
20
+ transport: z.literal("sse"),
21
+ url: z.string().min(1),
22
+ headers: z.record(z.string(), z.string()).default({}),
23
+ });
24
+
25
+ export const mcpServerSchema = z.discriminatedUnion("transport", [
26
+ stdioConnectionSchema,
27
+ httpConnectionSchema,
28
+ sseConnectionSchema,
29
+ ]);
30
+
31
+ export type McpServerConnection = z.infer<typeof mcpServerSchema>;
32
+
33
+ /**
34
+ * 从 `MCP_SERVERS`(JSON)或已解析的对象中读取 MCP 连接配置。
35
+ *
36
+ * @example
37
+ * MCP_SERVERS='{"filesystem":{"transport":"stdio","command":"npx","args":["-y","@modelcontextprotocol/server-filesystem","."]}}'
38
+ */
39
+ export const loadMcpConnections = (
40
+ raw: string | undefined = process.env.MCP_SERVERS,
41
+ ): Record<string, McpServerConnection> => {
42
+ if (!raw || raw.trim() === "") return {};
43
+
44
+ let parsed: unknown;
45
+ try {
46
+ parsed = JSON.parse(raw);
47
+ } catch (error) {
48
+ throw new ConfigurationError(`MCP_SERVERS 必须是合法的 JSON:${errorMessage(error)}`);
49
+ }
50
+
51
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
52
+ throw new ConfigurationError("MCP_SERVERS 必须是以服务器名称为键的对象。");
53
+ }
54
+
55
+ const entries = Object.entries(parsed).map(([name, value]): [string, McpServerConnection] => {
56
+ const result = mcpServerSchema.safeParse(value);
57
+ if (!result.success) {
58
+ const issues = result.error.issues
59
+ .map((issue) => `${issue.path.join(".") || name}: ${issue.message}`)
60
+ .join("; ");
61
+ throw new ConfigurationError(`MCP 服务器 "${name}" 配置无效:${issues}`);
62
+ }
63
+
64
+ return [name, result.data];
65
+ });
66
+
67
+ return Object.fromEntries(entries);
68
+ };
@@ -0,0 +1,10 @@
1
+ import { McpToolRegistry } from "./registry.js";
2
+
3
+ export { createMcpAdapter, loadMcpTools } from "./client.js";
4
+ export { loadMcpConnections, mcpServerSchema, type McpServerConnection } from "./connections.js";
5
+ export { McpToolRegistry };
6
+
7
+ /** 启动时加载一次 MCP 工具;未配置时返回空注册表。 */
8
+ export const createMcpToolRegistry = async (): Promise<McpToolRegistry> => {
9
+ return McpToolRegistry.create();
10
+ };
@@ -0,0 +1,45 @@
1
+ import type { DynamicStructuredTool } from "@langchain/core/tools";
2
+ import type { MCPAdapter } from "@langchain/mcp-adapters";
3
+
4
+ import { loadMcpTools } from "./client.js";
5
+ import { loadMcpConnections, type McpServerConnection } from "./connections.js";
6
+
7
+ /**
8
+ * 持有整个进程生命周期的 MCP 适配器。启动时加载一次工具并交给主 Agent;
9
+ * 关闭时断开连接。
10
+ */
11
+ export class McpToolRegistry {
12
+ readonly tools: DynamicStructuredTool[];
13
+ private readonly adapter: MCPAdapter | null;
14
+ private readonly servers: string[];
15
+
16
+ private constructor(
17
+ adapter: MCPAdapter | null,
18
+ tools: DynamicStructuredTool[],
19
+ servers: string[],
20
+ ) {
21
+ this.adapter = adapter;
22
+ this.tools = tools;
23
+ this.servers = servers;
24
+ }
25
+
26
+ static async create(
27
+ connections: Record<string, McpServerConnection> = loadMcpConnections(),
28
+ ): Promise<McpToolRegistry> {
29
+ if (Object.keys(connections).length === 0) {
30
+ return new McpToolRegistry(null, [], []);
31
+ }
32
+
33
+ const { adapter, tools } = await loadMcpTools(connections);
34
+
35
+ return new McpToolRegistry(adapter, tools, Object.keys(connections));
36
+ }
37
+
38
+ get serverNames(): string[] {
39
+ return [...this.servers];
40
+ }
41
+
42
+ async close(): Promise<void> {
43
+ await this.adapter?.close();
44
+ }
45
+ }
@@ -0,0 +1,95 @@
1
+ export type ErrorDetails = Record<string, unknown>;
2
+
3
+ export interface AppErrorOptions {
4
+ status?: number;
5
+ code?: string;
6
+ details?: ErrorDetails;
7
+ cause?: unknown;
8
+ }
9
+
10
+ /**
11
+ * 可以安全通过 HTTP API 暴露的错误基类。
12
+ * 非 AppError 的错误统一按 500 处理。
13
+ */
14
+ export class AppError extends Error {
15
+ readonly status: number;
16
+ readonly code: string;
17
+ readonly details?: ErrorDetails;
18
+
19
+ constructor(message: string, options: AppErrorOptions = {}) {
20
+ super(message, { cause: options.cause });
21
+ this.name = new.target.name;
22
+ this.status = options.status ?? 500;
23
+ this.code = options.code ?? "INTERNAL_ERROR";
24
+ this.details = options.details;
25
+ }
26
+
27
+ toJSON(): { error: { code: string; message: string; details?: ErrorDetails } } {
28
+ return {
29
+ error: {
30
+ code: this.code,
31
+ message: this.message,
32
+ ...(this.details ? { details: this.details } : {}),
33
+ },
34
+ };
35
+ }
36
+ }
37
+
38
+ export class ConfigurationError extends AppError {
39
+ constructor(message: string, details?: ErrorDetails) {
40
+ super(message, { status: 500, code: "CONFIGURATION_ERROR", details });
41
+ }
42
+ }
43
+
44
+ export class ValidationError extends AppError {
45
+ constructor(message: string, details?: ErrorDetails) {
46
+ super(message, { status: 400, code: "VALIDATION_ERROR", details });
47
+ }
48
+ }
49
+
50
+ export class UnauthorizedError extends AppError {
51
+ constructor(message = "缺少凭证或凭证无效。") {
52
+ super(message, { status: 401, code: "UNAUTHORIZED" });
53
+ }
54
+ }
55
+
56
+ export class NotFoundError extends AppError {
57
+ constructor(message = "资源不存在。") {
58
+ super(message, { status: 404, code: "NOT_FOUND" });
59
+ }
60
+ }
61
+
62
+ export class ConflictError extends AppError {
63
+ constructor(message = "资源冲突。") {
64
+ super(message, { status: 409, code: "CONFLICT" });
65
+ }
66
+ }
67
+
68
+ export interface ErrorResponseBody {
69
+ error: {
70
+ code: string;
71
+ message: string;
72
+ details?: ErrorDetails;
73
+ };
74
+ }
75
+
76
+ export const toErrorResponse = (
77
+ error: unknown,
78
+ ): {
79
+ status: number;
80
+ body: ErrorResponseBody;
81
+ } => {
82
+ if (error instanceof AppError) {
83
+ return { status: error.status, body: error.toJSON() };
84
+ }
85
+
86
+ return {
87
+ status: 500,
88
+ body: {
89
+ error: {
90
+ code: "INTERNAL_ERROR",
91
+ message: error instanceof Error ? error.message : "发生了未预期的错误。",
92
+ },
93
+ },
94
+ };
95
+ };