create-deepagent-server 0.0.0-stage → 0.1.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -2
  3. package/bin/create-deepagent-server.js +27 -0
  4. package/package.json +50 -4
  5. package/src/args.js +193 -0
  6. package/src/cli.js +269 -0
  7. package/src/dependencies.js +34 -0
  8. package/src/prompts.js +85 -0
  9. package/src/registry.js +68 -0
  10. package/src/scaffold.js +182 -0
  11. package/src/setup.js +77 -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 +74 -0
  17. package/templates/deepagent/js/scripts/dev.js +31 -0
  18. package/templates/deepagent/js/src/agents/factory.js +10 -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 +44 -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/subagents/researcher.md +16 -0
  25. package/templates/deepagent/js/src/agents/prompts/supervisor.js +17 -0
  26. package/templates/deepagent/js/src/agents/prompts/supervisor.md +42 -0
  27. package/templates/deepagent/js/src/agents/state/index.js +1 -0
  28. package/templates/deepagent/js/src/agents/state/types.js +10 -0
  29. package/templates/deepagent/js/src/agents/subagents/analyst.js +11 -0
  30. package/templates/deepagent/js/src/agents/subagents/coder.js +11 -0
  31. package/templates/deepagent/js/src/agents/subagents/index.js +8 -0
  32. package/templates/deepagent/js/src/agents/subagents/researcher.js +12 -0
  33. package/templates/deepagent/js/src/agents/supervisor.js +56 -0
  34. package/templates/deepagent/js/src/api/app.js +22 -0
  35. package/templates/deepagent/js/src/api/middleware/auth.js +27 -0
  36. package/templates/deepagent/js/src/api/middleware/error.js +26 -0
  37. package/templates/deepagent/js/src/api/routes/agent.js +73 -0
  38. package/templates/deepagent/js/src/api/routes/health.js +31 -0
  39. package/templates/deepagent/js/src/api/routes/session.js +62 -0
  40. package/templates/deepagent/js/src/app.js +79 -0
  41. package/templates/deepagent/js/src/backends/composite.js +20 -0
  42. package/templates/deepagent/js/src/backends/filesystem.js +8 -0
  43. package/templates/deepagent/js/src/backends/index.js +28 -0
  44. package/templates/deepagent/js/src/backends/sandbox.js +23 -0
  45. package/templates/deepagent/js/src/config/agent.js +13 -0
  46. package/templates/deepagent/js/src/config/env.js +73 -0
  47. package/templates/deepagent/js/src/config/index.js +35 -0
  48. package/templates/deepagent/js/src/config/model.js +34 -0
  49. package/templates/deepagent/js/src/graph/checkpointer.js +20 -0
  50. package/templates/deepagent/js/src/graph/compile.js +8 -0
  51. package/templates/deepagent/js/src/graph/index.js +3 -0
  52. package/templates/deepagent/js/src/graph/store.js +20 -0
  53. package/templates/deepagent/js/src/index.js +32 -0
  54. package/templates/deepagent/js/src/infrastructure/database/client.js +43 -0
  55. package/templates/deepagent/js/src/infrastructure/database/migrations/001_init.sql +20 -0
  56. package/templates/deepagent/js/src/infrastructure/logger/index.js +19 -0
  57. package/templates/deepagent/js/src/infrastructure/redis/client.js +45 -0
  58. package/templates/deepagent/js/src/infrastructure/shutdown/index.js +51 -0
  59. package/templates/deepagent/js/src/memory/index.js +6 -0
  60. package/templates/deepagent/js/src/memory/manager.js +39 -0
  61. package/templates/deepagent/js/src/memory/store.js +36 -0
  62. package/templates/deepagent/js/src/middleware/approval.js +42 -0
  63. package/templates/deepagent/js/src/middleware/context.js +30 -0
  64. package/templates/deepagent/js/src/middleware/index.js +9 -0
  65. package/templates/deepagent/js/src/middleware/logging.js +66 -0
  66. package/templates/deepagent/js/src/middleware/security.js +51 -0
  67. package/templates/deepagent/js/src/schemas/agent.js +33 -0
  68. package/templates/deepagent/js/src/schemas/common.js +19 -0
  69. package/templates/deepagent/js/src/schemas/locale.js +3 -0
  70. package/templates/deepagent/js/src/schemas/session.js +23 -0
  71. package/templates/deepagent/js/src/services/agent.service.js +117 -0
  72. package/templates/deepagent/js/src/services/memory.service.js +27 -0
  73. package/templates/deepagent/js/src/services/session.service.js +92 -0
  74. package/templates/deepagent/js/src/skills/index.js +17 -0
  75. package/templates/deepagent/js/src/skills/loader.js +65 -0
  76. package/templates/deepagent/js/src/tools/database/index.js +1 -0
  77. package/templates/deepagent/js/src/tools/database/query.js +62 -0
  78. package/templates/deepagent/js/src/tools/filesystem/index.js +86 -0
  79. package/templates/deepagent/js/src/tools/index.js +30 -0
  80. package/templates/deepagent/js/src/tools/mcp/client.js +35 -0
  81. package/templates/deepagent/js/src/tools/mcp/connections.js +54 -0
  82. package/templates/deepagent/js/src/tools/mcp/index.js +8 -0
  83. package/templates/deepagent/js/src/tools/mcp/registry.js +32 -0
  84. package/templates/deepagent/js/src/tools/search/index.js +1 -0
  85. package/templates/deepagent/js/src/tools/search/web-search.js +54 -0
  86. package/templates/deepagent/js/src/utils/errors.js +64 -0
  87. package/templates/deepagent/js/src/utils/helpers.js +42 -0
  88. package/templates/deepagent/js/tests/agents/prompts.test.js +24 -0
  89. package/templates/deepagent/js/tests/agents/supervisor.test.js +34 -0
  90. package/templates/deepagent/js/tests/integration/api.test.js +99 -0
  91. package/templates/deepagent/js/tests/middleware/security.test.js +24 -0
  92. package/templates/deepagent/js/tests/tools/query.test.js +23 -0
  93. package/templates/deepagent/shared/README.md +162 -0
  94. package/templates/deepagent/shared/_editorconfig +12 -0
  95. package/templates/deepagent/shared/_env.example +56 -0
  96. package/templates/deepagent/shared/_gitignore +22 -0
  97. package/templates/deepagent/shared/deployment/docker-compose.yml +56 -0
  98. package/templates/deepagent/shared/resources/AGENTS.md +32 -0
  99. package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
  100. package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
  101. package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
  102. package/templates/deepagent/shared/skills/research/SKILL.md +31 -0
  103. package/templates/deepagent/shared/workspaces/README.md +5 -0
  104. package/templates/deepagent/ts/deployment/Dockerfile +25 -0
  105. package/templates/deepagent/ts/scripts/check.ts +91 -0
  106. package/templates/deepagent/ts/scripts/copy-assets.ts +35 -0
  107. package/templates/deepagent/ts/scripts/dev.ts +40 -0
  108. package/templates/deepagent/ts/src/agents/factory.ts +11 -0
  109. package/templates/deepagent/ts/src/agents/index.ts +4 -0
  110. package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
  111. package/templates/deepagent/ts/src/agents/prompts/loader.ts +52 -0
  112. package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
  113. package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
  114. package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +16 -0
  115. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +42 -0
  116. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
  117. package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
  118. package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
  119. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +14 -0
  120. package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
  121. package/templates/deepagent/ts/src/agents/subagents/index.ts +10 -0
  122. package/templates/deepagent/ts/src/agents/subagents/researcher.ts +15 -0
  123. package/templates/deepagent/ts/src/agents/supervisor.ts +80 -0
  124. package/templates/deepagent/ts/src/api/app.ts +48 -0
  125. package/templates/deepagent/ts/src/api/middleware/auth.ts +37 -0
  126. package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
  127. package/templates/deepagent/ts/src/api/routes/agent.ts +93 -0
  128. package/templates/deepagent/ts/src/api/routes/health.ts +45 -0
  129. package/templates/deepagent/ts/src/api/routes/session.ts +77 -0
  130. package/templates/deepagent/ts/src/app.ts +104 -0
  131. package/templates/deepagent/ts/src/backends/composite.ts +34 -0
  132. package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
  133. package/templates/deepagent/ts/src/backends/index.ts +42 -0
  134. package/templates/deepagent/ts/src/backends/sandbox.ts +32 -0
  135. package/templates/deepagent/ts/src/config/agent.ts +37 -0
  136. package/templates/deepagent/ts/src/config/env.ts +102 -0
  137. package/templates/deepagent/ts/src/config/index.ts +76 -0
  138. package/templates/deepagent/ts/src/config/model.ts +49 -0
  139. package/templates/deepagent/ts/src/graph/checkpointer.ts +26 -0
  140. package/templates/deepagent/ts/src/graph/compile.ts +15 -0
  141. package/templates/deepagent/ts/src/graph/index.ts +3 -0
  142. package/templates/deepagent/ts/src/graph/store.ts +26 -0
  143. package/templates/deepagent/ts/src/index.ts +39 -0
  144. package/templates/deepagent/ts/src/infrastructure/database/client.ts +61 -0
  145. package/templates/deepagent/ts/src/infrastructure/database/migrations/001_init.sql +20 -0
  146. package/templates/deepagent/ts/src/infrastructure/logger/index.ts +25 -0
  147. package/templates/deepagent/ts/src/infrastructure/redis/client.ts +64 -0
  148. package/templates/deepagent/ts/src/infrastructure/shutdown/index.ts +85 -0
  149. package/templates/deepagent/ts/src/memory/index.ts +11 -0
  150. package/templates/deepagent/ts/src/memory/manager.ts +74 -0
  151. package/templates/deepagent/ts/src/memory/store.ts +57 -0
  152. package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
  153. package/templates/deepagent/ts/src/middleware/context.ts +37 -0
  154. package/templates/deepagent/ts/src/middleware/index.ts +9 -0
  155. package/templates/deepagent/ts/src/middleware/logging.ts +72 -0
  156. package/templates/deepagent/ts/src/middleware/security.ts +60 -0
  157. package/templates/deepagent/ts/src/schemas/agent.ts +48 -0
  158. package/templates/deepagent/ts/src/schemas/common.ts +26 -0
  159. package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
  160. package/templates/deepagent/ts/src/schemas/session.ts +31 -0
  161. package/templates/deepagent/ts/src/services/agent.service.ts +170 -0
  162. package/templates/deepagent/ts/src/services/memory.service.ts +43 -0
  163. package/templates/deepagent/ts/src/services/session.service.ts +148 -0
  164. package/templates/deepagent/ts/src/skills/index.ts +26 -0
  165. package/templates/deepagent/ts/src/skills/loader.ts +94 -0
  166. package/templates/deepagent/ts/src/tools/database/index.ts +1 -0
  167. package/templates/deepagent/ts/src/tools/database/query.ts +71 -0
  168. package/templates/deepagent/ts/src/tools/filesystem/index.ts +108 -0
  169. package/templates/deepagent/ts/src/tools/index.ts +41 -0
  170. package/templates/deepagent/ts/src/tools/mcp/client.ts +53 -0
  171. package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
  172. package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
  173. package/templates/deepagent/ts/src/tools/mcp/registry.ts +48 -0
  174. package/templates/deepagent/ts/src/tools/search/index.ts +1 -0
  175. package/templates/deepagent/ts/src/tools/search/web-search.ts +82 -0
  176. package/templates/deepagent/ts/src/utils/errors.ts +95 -0
  177. package/templates/deepagent/ts/src/utils/helpers.ts +52 -0
  178. package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
  179. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
  180. package/templates/deepagent/ts/tests/integration/api.test.ts +123 -0
  181. package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
  182. package/templates/deepagent/ts/tests/tools/query.test.ts +27 -0
  183. package/templates/deepagent/ts/tsconfig.json +19 -0
@@ -0,0 +1,94 @@
1
+ import type { Dirent } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ export interface SkillMetadata {
6
+ name: string;
7
+ description: string;
8
+ /** 包含 SKILL.md 的目录。 */
9
+ directory: string;
10
+ /** SKILL.md 的绝对路径。 */
11
+ file: string;
12
+ }
13
+
14
+ export interface SkillFrontmatter {
15
+ name?: string;
16
+ description?: string;
17
+ }
18
+
19
+ /** 不依赖 YAML 库,解析 SKILL.md 的 frontmatter。 */
20
+ export const parseSkillFrontmatter = (content: string): SkillFrontmatter => {
21
+ if (!content.startsWith("---")) return {};
22
+
23
+ const end = content.indexOf("\n---", 3);
24
+ if (end === -1) return {};
25
+
26
+ const frontmatter = content.slice(3, end);
27
+ const fields: Record<string, string> = {};
28
+
29
+ for (const line of frontmatter.split("\n")) {
30
+ const separator = line.indexOf(":");
31
+ if (separator === -1) continue;
32
+
33
+ const key = line.slice(0, separator).trim();
34
+ const value = line
35
+ .slice(separator + 1)
36
+ .trim()
37
+ .replace(/^["']|["']$/g, "");
38
+
39
+ if (key) fields[key] = value;
40
+ }
41
+
42
+ return {
43
+ ...(fields.name ? { name: fields.name } : {}),
44
+ ...(fields.description ? { description: fields.description } : {}),
45
+ };
46
+ };
47
+
48
+ /** 读取目录;目录不存在时返回空数组。 */
49
+ const readDirectory = async (directory: string): Promise<Dirent[]> => {
50
+ try {
51
+ return await fs.readdir(directory, { withFileTypes: true });
52
+ } catch (error) {
53
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
54
+ throw error;
55
+ }
56
+ };
57
+
58
+ /** 读取文本文件;文件不存在时返回 null。 */
59
+ const readTextFile = async (file: string): Promise<string | null> => {
60
+ try {
61
+ return await fs.readFile(file, "utf8");
62
+ } catch (error) {
63
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
64
+ throw error;
65
+ }
66
+ };
67
+
68
+ /**
69
+ * 扫描 `rootDir` 下包含 SKILL.md 的子目录。
70
+ * 目录不存在时返回空数组,保证没有技能时也能启动。
71
+ */
72
+ export const discoverSkills = async (rootDir: string): Promise<SkillMetadata[]> => {
73
+ const entries = await readDirectory(rootDir);
74
+ const skills: SkillMetadata[] = [];
75
+
76
+ for (const entry of entries) {
77
+ if (!entry.isDirectory()) continue;
78
+
79
+ const directory = path.join(rootDir, entry.name);
80
+ const file = path.join(directory, "SKILL.md");
81
+ const content = await readTextFile(file);
82
+ if (content === null) continue;
83
+
84
+ const metadata = parseSkillFrontmatter(content);
85
+ skills.push({
86
+ name: metadata.name ?? entry.name,
87
+ description: metadata.description ?? "",
88
+ directory,
89
+ file,
90
+ });
91
+ }
92
+
93
+ return skills.sort((a, b) => a.name.localeCompare(b.name));
94
+ };
@@ -0,0 +1 @@
1
+ export { assertReadOnlyQuery, queryDatabaseTool } from "./query.js";
@@ -0,0 +1,71 @@
1
+ import { tool } from "@langchain/core/tools";
2
+ import { z } from "zod";
3
+
4
+ import { getPool } from "../../infrastructure/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
+ /** 只读、参数化的 PostgreSQL 查询工具。 */
38
+ export const queryDatabaseTool = tool(
39
+ async ({ sql, params, limit }: z.infer<typeof querySchema>) => {
40
+ assertReadOnlyQuery(sql);
41
+
42
+ const client = await getPool().connect();
43
+
44
+ try {
45
+ await client.query("BEGIN TRANSACTION READ ONLY");
46
+ await client.query("SET LOCAL statement_timeout = '10s'");
47
+ const result = await client.query(sql, params);
48
+ await client.query("COMMIT");
49
+
50
+ return JSON.stringify(
51
+ {
52
+ rowCount: result.rowCount,
53
+ truncated: result.rows.length > limit,
54
+ rows: result.rows.slice(0, limit),
55
+ },
56
+ null,
57
+ 2,
58
+ );
59
+ } catch (error) {
60
+ await client.query("ROLLBACK").catch(() => undefined);
61
+ throw error;
62
+ } finally {
63
+ client.release();
64
+ }
65
+ },
66
+ {
67
+ name: "query_database",
68
+ description: "对应用 PostgreSQL 执行单条只读 SQL,并以 JSON 返回结果行。",
69
+ schema: querySchema,
70
+ },
71
+ );
@@ -0,0 +1,108 @@
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
+ if (append) {
63
+ await fs.appendFile(resolved, content, "utf8");
64
+ } else {
65
+ await fs.writeFile(resolved, content, "utf8");
66
+ }
67
+ return `已写入 ${content.length} 个字符到 ${filePath}`;
68
+ },
69
+ {
70
+ name: "write_workspace_file",
71
+ description: "在 Agent 工作区中创建或覆盖文件,也可以选择追加内容。",
72
+ schema: writeSchema,
73
+ },
74
+ );
75
+
76
+ const listSchema = z.object({
77
+ directory: z.string().default("."),
78
+ recursive: z.boolean().default(false),
79
+ });
80
+
81
+ const listFiles = tool(
82
+ async ({ directory, recursive }: z.infer<typeof listSchema>) => {
83
+ const resolved = resolveInsideRoot(rootDir, directory);
84
+ const entries = await fs.readdir(resolved, {
85
+ recursive,
86
+ withFileTypes: true,
87
+ });
88
+
89
+ const files = entries
90
+ .map((entry) => ({
91
+ name: entry.name,
92
+ path: nodePath.relative(rootDir, nodePath.join(entry.parentPath, entry.name)),
93
+ type: entry.isDirectory() ? "目录" : "文件",
94
+ }))
95
+ .sort((a, b) => a.path.localeCompare(b.path))
96
+ .slice(0, 500);
97
+
98
+ return JSON.stringify({ root: directory, files }, null, 2);
99
+ },
100
+ {
101
+ name: "list_workspace_files",
102
+ description: "列出 Agent 工作区中的文件和目录,不读取文件内容。",
103
+ schema: listSchema,
104
+ },
105
+ );
106
+
107
+ return [readFile, writeFile, listFiles];
108
+ };
@@ -0,0 +1,41 @@
1
+ import type { StructuredToolInterface } from "@langchain/core/tools";
2
+
3
+ import { queryDatabaseTool } from "./database/index.js";
4
+ import { createWorkspaceTools } from "./filesystem/index.js";
5
+ import { webSearchTool } from "./search/index.js";
6
+
7
+ export { assertReadOnlyQuery, queryDatabaseTool } from "./database/index.js";
8
+ export { createWorkspaceTools } from "./filesystem/index.js";
9
+ export {
10
+ createMcpAdapter,
11
+ createMcpToolRegistry,
12
+ loadMcpConnections,
13
+ loadMcpTools,
14
+ McpToolRegistry,
15
+ mcpServerSchema,
16
+ type McpServerConnection,
17
+ } from "./mcp/index.js";
18
+ export { createWebSearchTool, webSearchTool } from "./search/index.js";
19
+
20
+ export interface DefaultToolsOptions {
21
+ workspaceRoot: string;
22
+ enableDatabase?: boolean;
23
+ additionalTools?: StructuredToolInterface[];
24
+ }
25
+
26
+ /**
27
+ * 主 Agent 和子 Agent 可用的工具,位于 Deep Agents 内置工具
28
+ * (write_todos、read_file、write_file、task 等)之上。
29
+ */
30
+ export const createDefaultTools = ({
31
+ workspaceRoot,
32
+ enableDatabase = Boolean(process.env.DATABASE_URL),
33
+ additionalTools = [],
34
+ }: DefaultToolsOptions): StructuredToolInterface[] => {
35
+ return [
36
+ webSearchTool,
37
+ ...(enableDatabase ? [queryDatabaseTool] : []),
38
+ ...createWorkspaceTools({ rootDir: workspaceRoot }),
39
+ ...additionalTools,
40
+ ];
41
+ };
@@ -0,0 +1,53 @@
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
+ return { adapter, tools };
53
+ };
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
2
+
3
+ import { ConfigurationError } from "../../utils/errors.js";
4
+
5
+ const stdioConnectionSchema = z.object({
6
+ transport: z.literal("stdio"),
7
+ command: z.string().min(1),
8
+ args: z.array(z.string()).default([]),
9
+ env: z.record(z.string(), z.string()).default({}),
10
+ });
11
+
12
+ const httpConnectionSchema = z.object({
13
+ transport: z.literal("http"),
14
+ url: z.string().min(1),
15
+ headers: z.record(z.string(), z.string()).default({}),
16
+ });
17
+
18
+ const sseConnectionSchema = z.object({
19
+ transport: z.literal("sse"),
20
+ url: z.string().min(1),
21
+ headers: z.record(z.string(), z.string()).default({}),
22
+ });
23
+
24
+ export const mcpServerSchema = z.discriminatedUnion("transport", [
25
+ stdioConnectionSchema,
26
+ httpConnectionSchema,
27
+ sseConnectionSchema,
28
+ ]);
29
+
30
+ export type McpServerConnection = z.infer<typeof mcpServerSchema>;
31
+
32
+ /**
33
+ * 从 `MCP_SERVERS`(JSON)或已解析的对象中读取 MCP 连接配置。
34
+ *
35
+ * @example
36
+ * MCP_SERVERS='{"filesystem":{"transport":"stdio","command":"npx","args":["-y","@modelcontextprotocol/server-filesystem","."]}}'
37
+ */
38
+ export const loadMcpConnections = (
39
+ raw: string | undefined = process.env.MCP_SERVERS,
40
+ ): Record<string, McpServerConnection> => {
41
+ if (!raw || raw.trim() === "") return {};
42
+
43
+ let parsed: unknown;
44
+ try {
45
+ parsed = JSON.parse(raw);
46
+ } catch (error) {
47
+ throw new ConfigurationError(
48
+ `MCP_SERVERS 必须是合法的 JSON:${error instanceof Error ? error.message : String(error)}`,
49
+ );
50
+ }
51
+
52
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
53
+ throw new ConfigurationError("MCP_SERVERS 必须是以服务器名称为键的对象。");
54
+ }
55
+
56
+ const entries = Object.entries(parsed).map(([name, value]): [string, McpServerConnection] => {
57
+ const result = mcpServerSchema.safeParse(value);
58
+ if (!result.success) {
59
+ const issues = result.error.issues
60
+ .map((issue) => `${issue.path.join(".") || name}: ${issue.message}`)
61
+ .join("; ");
62
+ throw new ConfigurationError(`MCP 服务器 "${name}" 配置无效:${issues}`);
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,48 @@
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 #adapter: MCPAdapter | null;
13
+ readonly #tools: DynamicStructuredTool[];
14
+ 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
+ return new McpToolRegistry(adapter, tools, Object.keys(connections));
35
+ }
36
+
37
+ get tools(): DynamicStructuredTool[] {
38
+ return this.#tools;
39
+ }
40
+
41
+ get serverNames(): string[] {
42
+ return [...this.#servers];
43
+ }
44
+
45
+ async close(): Promise<void> {
46
+ await this.#adapter?.close();
47
+ }
48
+ }
@@ -0,0 +1 @@
1
+ export { createWebSearchTool, webSearchTool, type WebSearchToolOptions } from "./web-search.js";
@@ -0,0 +1,82 @@
1
+ import { tool } from "@langchain/core/tools";
2
+ import { z } from "zod";
3
+
4
+ const TAVILY_ENDPOINT = "https://api.tavily.com/search";
5
+
6
+ interface TavilyResult {
7
+ title?: string;
8
+ url?: string;
9
+ content?: string;
10
+ score?: number;
11
+ }
12
+
13
+ interface TavilyResponse {
14
+ answer?: string;
15
+ results?: TavilyResult[];
16
+ }
17
+
18
+ export interface WebSearchToolOptions {
19
+ apiKey?: string;
20
+ maxResults?: number;
21
+ }
22
+
23
+ const webSearchSchema = z.object({
24
+ query: z.string().min(2).describe("搜索关键词。"),
25
+ maxResults: z.number().int().min(1).max(10).default(5).describe("返回结果数量(1-10)。"),
26
+ });
27
+
28
+ /**
29
+ * 基于 Tavily 的 Web 搜索。API Key 延迟读取,因此即使未配置搜索也能注册
30
+ * 该工具;真正调用时会返回清晰错误,供模型报告。
31
+ */
32
+ export const createWebSearchTool = ({
33
+ apiKey,
34
+ maxResults: defaultMaxResults = 5,
35
+ }: WebSearchToolOptions = {}) => {
36
+ return tool(
37
+ async ({ query, maxResults }: z.infer<typeof webSearchSchema>) => {
38
+ const key = apiKey ?? process.env.TAVILY_API_KEY;
39
+ if (!key) {
40
+ throw new Error("未设置 TAVILY_API_KEY。请在 .env 中添加后启用 Web 搜索。");
41
+ }
42
+
43
+ const response = await fetch(TAVILY_ENDPOINT, {
44
+ method: "POST",
45
+ headers: { "content-type": "application/json" },
46
+ body: JSON.stringify({
47
+ api_key: key,
48
+ query,
49
+ max_results: Math.min(maxResults ?? defaultMaxResults, 10),
50
+ search_depth: "basic",
51
+ include_answer: false,
52
+ include_raw_content: false,
53
+ }),
54
+ signal: AbortSignal.timeout(20_000),
55
+ });
56
+
57
+ if (!response.ok) {
58
+ const detail = await response.text().catch(() => "");
59
+ throw new Error(
60
+ `Web 搜索失败,HTTP ${response.status}${detail ? `:${detail.slice(0, 300)}` : ""}`,
61
+ );
62
+ }
63
+
64
+ const data = (await response.json()) as TavilyResponse;
65
+ const results = (data.results ?? []).map((result) => ({
66
+ title: result.title ?? "",
67
+ url: result.url ?? "",
68
+ snippet: result.content ?? "",
69
+ score: result.score ?? 0,
70
+ }));
71
+
72
+ return JSON.stringify({ query, results }, null, 2);
73
+ },
74
+ {
75
+ name: "web_search",
76
+ description: "搜索公开网络,返回标题、URL 和摘要。用于获取最新信息,并引用实际使用的来源。",
77
+ schema: webSearchSchema,
78
+ },
79
+ );
80
+ };
81
+
82
+ export const webSearchTool = createWebSearchTool();
@@ -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
+ };