ultra-mcp-toolkit 1.6.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 (290) hide show
  1. package/.claude/skills/ultra-mcp-toolkit/SKILL.md +65 -0
  2. package/.claude/skills/ultra-mcp-toolkit/references/dispatcher.md +144 -0
  3. package/.claude/skills/ultra-mcp-toolkit/references/manifest.md +100 -0
  4. package/.claude/skills/ultra-mcp-toolkit/references/server-boot.md +260 -0
  5. package/.claude/skills/ultra-mcp-toolkit/references/skills.md +94 -0
  6. package/.claude/skills/ultra-mcp-toolkit/references/trim.md +115 -0
  7. package/LICENSE +21 -0
  8. package/README.md +271 -0
  9. package/build/agent-safety/index.d.ts +3 -0
  10. package/build/agent-safety/index.d.ts.map +1 -0
  11. package/build/agent-safety/index.js +3 -0
  12. package/build/agent-safety/index.js.map +1 -0
  13. package/build/agent-safety/safe-path.d.ts +67 -0
  14. package/build/agent-safety/safe-path.d.ts.map +1 -0
  15. package/build/agent-safety/safe-path.js +157 -0
  16. package/build/agent-safety/safe-path.js.map +1 -0
  17. package/build/agent-safety/safe-path.test.d.ts +2 -0
  18. package/build/agent-safety/safe-path.test.d.ts.map +1 -0
  19. package/build/agent-safety/safe-path.test.js +134 -0
  20. package/build/agent-safety/safe-path.test.js.map +1 -0
  21. package/build/agent-safety/safety-checker.d.ts +52 -0
  22. package/build/agent-safety/safety-checker.d.ts.map +1 -0
  23. package/build/agent-safety/safety-checker.js +218 -0
  24. package/build/agent-safety/safety-checker.js.map +1 -0
  25. package/build/agent-safety/safety-checker.test.d.ts +2 -0
  26. package/build/agent-safety/safety-checker.test.d.ts.map +1 -0
  27. package/build/agent-safety/safety-checker.test.js +138 -0
  28. package/build/agent-safety/safety-checker.test.js.map +1 -0
  29. package/build/agent-tools/file-tools.d.ts +93 -0
  30. package/build/agent-tools/file-tools.d.ts.map +1 -0
  31. package/build/agent-tools/file-tools.js +164 -0
  32. package/build/agent-tools/file-tools.js.map +1 -0
  33. package/build/agent-tools/file-tools.test.d.ts +2 -0
  34. package/build/agent-tools/file-tools.test.d.ts.map +1 -0
  35. package/build/agent-tools/file-tools.test.js +186 -0
  36. package/build/agent-tools/file-tools.test.js.map +1 -0
  37. package/build/agent-tools/git-tools.d.ts +106 -0
  38. package/build/agent-tools/git-tools.d.ts.map +1 -0
  39. package/build/agent-tools/git-tools.js +202 -0
  40. package/build/agent-tools/git-tools.js.map +1 -0
  41. package/build/agent-tools/github-tools.d.ts +151 -0
  42. package/build/agent-tools/github-tools.d.ts.map +1 -0
  43. package/build/agent-tools/github-tools.js +293 -0
  44. package/build/agent-tools/github-tools.js.map +1 -0
  45. package/build/agent-tools/index.d.ts +5 -0
  46. package/build/agent-tools/index.d.ts.map +1 -0
  47. package/build/agent-tools/index.js +5 -0
  48. package/build/agent-tools/index.js.map +1 -0
  49. package/build/agent-tools/test-tools.d.ts +79 -0
  50. package/build/agent-tools/test-tools.d.ts.map +1 -0
  51. package/build/agent-tools/test-tools.js +113 -0
  52. package/build/agent-tools/test-tools.js.map +1 -0
  53. package/build/boot/http.d.ts +31 -0
  54. package/build/boot/http.d.ts.map +1 -0
  55. package/build/boot/http.js +301 -0
  56. package/build/boot/http.js.map +1 -0
  57. package/build/boot/http.test.d.ts +2 -0
  58. package/build/boot/http.test.d.ts.map +1 -0
  59. package/build/boot/http.test.js +514 -0
  60. package/build/boot/http.test.js.map +1 -0
  61. package/build/boot/stdio.d.ts +14 -0
  62. package/build/boot/stdio.d.ts.map +1 -0
  63. package/build/boot/stdio.js +48 -0
  64. package/build/boot/stdio.js.map +1 -0
  65. package/build/bridge/client.d.ts +10 -0
  66. package/build/bridge/client.d.ts.map +1 -0
  67. package/build/bridge/client.js +85 -0
  68. package/build/bridge/client.js.map +1 -0
  69. package/build/bridge/discovery.d.ts +29 -0
  70. package/build/bridge/discovery.d.ts.map +1 -0
  71. package/build/bridge/discovery.js +202 -0
  72. package/build/bridge/discovery.js.map +1 -0
  73. package/build/bridge/discovery.test.d.ts +2 -0
  74. package/build/bridge/discovery.test.d.ts.map +1 -0
  75. package/build/bridge/discovery.test.js +140 -0
  76. package/build/bridge/discovery.test.js.map +1 -0
  77. package/build/bridge/index.d.ts +6 -0
  78. package/build/bridge/index.d.ts.map +1 -0
  79. package/build/bridge/index.js +10 -0
  80. package/build/bridge/index.js.map +1 -0
  81. package/build/bridge/resolve.d.ts +14 -0
  82. package/build/bridge/resolve.d.ts.map +1 -0
  83. package/build/bridge/resolve.js +22 -0
  84. package/build/bridge/resolve.js.map +1 -0
  85. package/build/bridge/server.d.ts +39 -0
  86. package/build/bridge/server.d.ts.map +1 -0
  87. package/build/bridge/server.js +237 -0
  88. package/build/bridge/server.js.map +1 -0
  89. package/build/bridge/wire.d.ts +23 -0
  90. package/build/bridge/wire.d.ts.map +1 -0
  91. package/build/bridge/wire.js +17 -0
  92. package/build/bridge/wire.js.map +1 -0
  93. package/build/cli/help-select.test.d.ts +2 -0
  94. package/build/cli/help-select.test.d.ts.map +1 -0
  95. package/build/cli/help-select.test.js +215 -0
  96. package/build/cli/help-select.test.js.map +1 -0
  97. package/build/cli/help.d.ts +17 -0
  98. package/build/cli/help.d.ts.map +1 -0
  99. package/build/cli/help.js +91 -0
  100. package/build/cli/help.js.map +1 -0
  101. package/build/cli/index.d.ts +31 -0
  102. package/build/cli/index.d.ts.map +1 -0
  103. package/build/cli/index.js +387 -0
  104. package/build/cli/index.js.map +1 -0
  105. package/build/cli/install-skill.d.ts +20 -0
  106. package/build/cli/install-skill.d.ts.map +1 -0
  107. package/build/cli/install-skill.js +98 -0
  108. package/build/cli/install-skill.js.map +1 -0
  109. package/build/cli/install-skill.test.d.ts +2 -0
  110. package/build/cli/install-skill.test.d.ts.map +1 -0
  111. package/build/cli/install-skill.test.js +159 -0
  112. package/build/cli/install-skill.test.js.map +1 -0
  113. package/build/cli/parse-argv.d.ts +10 -0
  114. package/build/cli/parse-argv.d.ts.map +1 -0
  115. package/build/cli/parse-argv.js +95 -0
  116. package/build/cli/parse-argv.js.map +1 -0
  117. package/build/cli/select.d.ts +4 -0
  118. package/build/cli/select.d.ts.map +1 -0
  119. package/build/cli/select.js +53 -0
  120. package/build/cli/select.js.map +1 -0
  121. package/build/client/http.d.ts +32 -0
  122. package/build/client/http.d.ts.map +1 -0
  123. package/build/client/http.js +183 -0
  124. package/build/client/http.js.map +1 -0
  125. package/build/client/http.test.d.ts +2 -0
  126. package/build/client/http.test.d.ts.map +1 -0
  127. package/build/client/http.test.js +76 -0
  128. package/build/client/http.test.js.map +1 -0
  129. package/build/client/index.d.ts +9 -0
  130. package/build/client/index.d.ts.map +1 -0
  131. package/build/client/index.js +19 -0
  132. package/build/client/index.js.map +1 -0
  133. package/build/client/streaming.d.ts +29 -0
  134. package/build/client/streaming.d.ts.map +1 -0
  135. package/build/client/streaming.js +133 -0
  136. package/build/client/streaming.js.map +1 -0
  137. package/build/client/streaming.test.d.ts +2 -0
  138. package/build/client/streaming.test.d.ts.map +1 -0
  139. package/build/client/streaming.test.js +139 -0
  140. package/build/client/streaming.test.js.map +1 -0
  141. package/build/client/transport.d.ts +24 -0
  142. package/build/client/transport.d.ts.map +1 -0
  143. package/build/client/transport.js +119 -0
  144. package/build/client/transport.js.map +1 -0
  145. package/build/client/transport.test.d.ts +2 -0
  146. package/build/client/transport.test.d.ts.map +1 -0
  147. package/build/client/transport.test.js +145 -0
  148. package/build/client/transport.test.js.map +1 -0
  149. package/build/code-api/boot.d.ts +28 -0
  150. package/build/code-api/boot.d.ts.map +1 -0
  151. package/build/code-api/boot.js +57 -0
  152. package/build/code-api/boot.js.map +1 -0
  153. package/build/code-api/index.d.ts +4 -0
  154. package/build/code-api/index.d.ts.map +1 -0
  155. package/build/code-api/index.js +5 -0
  156. package/build/code-api/index.js.map +1 -0
  157. package/build/code-api/script.d.ts +17 -0
  158. package/build/code-api/script.d.ts.map +1 -0
  159. package/build/code-api/script.js +57 -0
  160. package/build/code-api/script.js.map +1 -0
  161. package/build/code-api/tool.d.ts +36 -0
  162. package/build/code-api/tool.d.ts.map +1 -0
  163. package/build/code-api/tool.js +91 -0
  164. package/build/code-api/tool.js.map +1 -0
  165. package/build/config/index.d.ts +23 -0
  166. package/build/config/index.d.ts.map +1 -0
  167. package/build/config/index.js +55 -0
  168. package/build/config/index.js.map +1 -0
  169. package/build/config/index.test.d.ts +2 -0
  170. package/build/config/index.test.d.ts.map +1 -0
  171. package/build/config/index.test.js +84 -0
  172. package/build/config/index.test.js.map +1 -0
  173. package/build/confirm/index.d.ts +57 -0
  174. package/build/confirm/index.d.ts.map +1 -0
  175. package/build/confirm/index.js +198 -0
  176. package/build/confirm/index.js.map +1 -0
  177. package/build/core/disk-cache.d.ts +8 -0
  178. package/build/core/disk-cache.d.ts.map +1 -0
  179. package/build/core/disk-cache.js +70 -0
  180. package/build/core/disk-cache.js.map +1 -0
  181. package/build/core/disk-cache.test.d.ts +2 -0
  182. package/build/core/disk-cache.test.d.ts.map +1 -0
  183. package/build/core/disk-cache.test.js +62 -0
  184. package/build/core/disk-cache.test.js.map +1 -0
  185. package/build/core/lru.d.ts +18 -0
  186. package/build/core/lru.d.ts.map +1 -0
  187. package/build/core/lru.js +57 -0
  188. package/build/core/lru.js.map +1 -0
  189. package/build/core/lru.test.d.ts +2 -0
  190. package/build/core/lru.test.d.ts.map +1 -0
  191. package/build/core/lru.test.js +86 -0
  192. package/build/core/lru.test.js.map +1 -0
  193. package/build/core/manifest.d.ts +63 -0
  194. package/build/core/manifest.d.ts.map +1 -0
  195. package/build/core/manifest.js +193 -0
  196. package/build/core/manifest.js.map +1 -0
  197. package/build/core/manifest.test.d.ts +2 -0
  198. package/build/core/manifest.test.d.ts.map +1 -0
  199. package/build/core/manifest.test.js +234 -0
  200. package/build/core/manifest.test.js.map +1 -0
  201. package/build/core/page-cache.d.ts +21 -0
  202. package/build/core/page-cache.d.ts.map +1 -0
  203. package/build/core/page-cache.js +152 -0
  204. package/build/core/page-cache.js.map +1 -0
  205. package/build/core/page-cache.test.d.ts +2 -0
  206. package/build/core/page-cache.test.d.ts.map +1 -0
  207. package/build/core/page-cache.test.js +93 -0
  208. package/build/core/page-cache.test.js.map +1 -0
  209. package/build/core/sandbox.d.ts +26 -0
  210. package/build/core/sandbox.d.ts.map +1 -0
  211. package/build/core/sandbox.js +150 -0
  212. package/build/core/sandbox.js.map +1 -0
  213. package/build/core/sandbox.test.d.ts +2 -0
  214. package/build/core/sandbox.test.d.ts.map +1 -0
  215. package/build/core/sandbox.test.js +80 -0
  216. package/build/core/sandbox.test.js.map +1 -0
  217. package/build/core/trim-registry.d.ts +5 -0
  218. package/build/core/trim-registry.d.ts.map +1 -0
  219. package/build/core/trim-registry.js +27 -0
  220. package/build/core/trim-registry.js.map +1 -0
  221. package/build/core/trim.d.ts +26 -0
  222. package/build/core/trim.d.ts.map +1 -0
  223. package/build/core/trim.js +99 -0
  224. package/build/core/trim.js.map +1 -0
  225. package/build/core/trim.test.d.ts +2 -0
  226. package/build/core/trim.test.d.ts.map +1 -0
  227. package/build/core/trim.test.js +131 -0
  228. package/build/core/trim.test.js.map +1 -0
  229. package/build/index.d.ts +25 -0
  230. package/build/index.d.ts.map +1 -0
  231. package/build/index.js +49 -0
  232. package/build/index.js.map +1 -0
  233. package/build/schemas/index.d.ts +6 -0
  234. package/build/schemas/index.d.ts.map +1 -0
  235. package/build/schemas/index.js +20 -0
  236. package/build/schemas/index.js.map +1 -0
  237. package/build/schemas/index.test.d.ts +2 -0
  238. package/build/schemas/index.test.d.ts.map +1 -0
  239. package/build/schemas/index.test.js +48 -0
  240. package/build/schemas/index.test.js.map +1 -0
  241. package/build/skills/drift.d.ts +18 -0
  242. package/build/skills/drift.d.ts.map +1 -0
  243. package/build/skills/drift.js +158 -0
  244. package/build/skills/drift.js.map +1 -0
  245. package/build/skills/drift.test.d.ts +2 -0
  246. package/build/skills/drift.test.d.ts.map +1 -0
  247. package/build/skills/drift.test.js +126 -0
  248. package/build/skills/drift.test.js.map +1 -0
  249. package/build/skills/files.d.ts +14 -0
  250. package/build/skills/files.d.ts.map +1 -0
  251. package/build/skills/files.js +80 -0
  252. package/build/skills/files.js.map +1 -0
  253. package/build/skills/files.test.d.ts +2 -0
  254. package/build/skills/files.test.d.ts.map +1 -0
  255. package/build/skills/files.test.js +54 -0
  256. package/build/skills/files.test.js.map +1 -0
  257. package/build/skills/index.d.ts +3 -0
  258. package/build/skills/index.d.ts.map +1 -0
  259. package/build/skills/index.js +8 -0
  260. package/build/skills/index.js.map +1 -0
  261. package/build/skills/serve.test.d.ts +2 -0
  262. package/build/skills/serve.test.d.ts.map +1 -0
  263. package/build/skills/serve.test.js +67 -0
  264. package/build/skills/serve.test.js.map +1 -0
  265. package/build/tool/dispatcher.d.ts +48 -0
  266. package/build/tool/dispatcher.d.ts.map +1 -0
  267. package/build/tool/dispatcher.js +219 -0
  268. package/build/tool/dispatcher.js.map +1 -0
  269. package/build/tool/dispatcher.test.d.ts +2 -0
  270. package/build/tool/dispatcher.test.d.ts.map +1 -0
  271. package/build/tool/dispatcher.test.js +269 -0
  272. package/build/tool/dispatcher.test.js.map +1 -0
  273. package/build/tool/schema-validation.test.d.ts +2 -0
  274. package/build/tool/schema-validation.test.d.ts.map +1 -0
  275. package/build/tool/schema-validation.test.js +56 -0
  276. package/build/tool/schema-validation.test.js.map +1 -0
  277. package/build/trim/mutation-ack.d.ts +11 -0
  278. package/build/trim/mutation-ack.d.ts.map +1 -0
  279. package/build/trim/mutation-ack.js +52 -0
  280. package/build/trim/mutation-ack.js.map +1 -0
  281. package/build/trim/mutation-ack.test.d.ts +2 -0
  282. package/build/trim/mutation-ack.test.d.ts.map +1 -0
  283. package/build/trim/mutation-ack.test.js +67 -0
  284. package/build/trim/mutation-ack.test.js.map +1 -0
  285. package/build/types/refs.d.ts +14 -0
  286. package/build/types/refs.d.ts.map +1 -0
  287. package/build/types/refs.js +9 -0
  288. package/build/types/refs.js.map +1 -0
  289. package/package.json +181 -0
  290. package/scripts/install-skill.mjs +128 -0
@@ -0,0 +1,115 @@
1
+ # Trim — shaping responses for the model
2
+
3
+ Trim functions are the toolkit's single biggest token-saving lever. They project a raw API response into a compact summary; the full response goes to the sandbox and surfaces only as a `ref` the model can follow.
4
+
5
+ ## The contract
6
+
7
+ ```ts
8
+ type TrimFn = (raw: unknown) => unknown;
9
+ ```
10
+
11
+ That's it. Pure function, no side effects, no async. Receives the raw response from `client[verb]`; returns the compact projection.
12
+
13
+ ## Allowlist, never denylist
14
+
15
+ ```ts
16
+ import { pick } from "ultra-mcp-toolkit/trim";
17
+
18
+ const issueSummary = (raw: unknown) => {
19
+ const r = raw as { key: string; fields: Record<string, unknown> };
20
+ return {
21
+ key: r.key,
22
+ ...pick(r.fields, ["summary", "status", "assignee"]),
23
+ };
24
+ };
25
+ ```
26
+
27
+ Why allowlist:
28
+ - New API fields default to dropped (safe behavior).
29
+ - The contract between server and model stays stable when the API adds noise.
30
+ - Reviewers see exactly what the model gets.
31
+
32
+ ## Registering trims
33
+
34
+ ```ts
35
+ import { createTrimRegistry } from "ultra-mcp-toolkit/trim-registry";
36
+
37
+ export const trimRegistry = createTrimRegistry({
38
+ issue: issueSummary,
39
+ page: pageSummary,
40
+ pullrequest: prSummary,
41
+ // The string key here matches `op.trim` on the manifest entry.
42
+ });
43
+ ```
44
+
45
+ The registry is type-safe (string keys → known set), and the dispatcher throws if a manifest entry references a key that isn't registered.
46
+
47
+ ## Helpers in `ultra-mcp-toolkit/trim`
48
+
49
+ - **`pick(obj, keys)`** — shallow copy of allowed keys. The workhorse.
50
+ - **`paginatedListSummary(raw, { total, startAt, maxResults })`** — for `{ total, startAt, maxResults, values }`-shaped responses (Jira, Confluence, Bitbucket). Drops `values` from the model's view but the ref still has them.
51
+ - **`bareListSummary(items, opts)`** — for endpoints that return a bare array with no envelope.
52
+ - **`extractNextCursor(raw)`** — pulls a `next` cursor / `_links.next` link out of API pagination metadata.
53
+ - **`safeHref(s)`** — strips `javascript:` and other unsafe schemes when piping HTML/ADF through to markdown.
54
+ - **`isPlainObject(v)`** — narrow type guard for the trim function input.
55
+
56
+ ## The `{ summary, ref }` envelope
57
+
58
+ `invokeOperation` does:
59
+ 1. raw response → trim → `summary`
60
+ 2. raw response → `sandbox.put(raw)` → `ref` (`refs:abc123…`)
61
+ 3. returns `{ summary, ref }`.
62
+
63
+ The model sees `summary` inline. If it needs full detail (PR diff, page body, full issue), it reads the ref. Two cache primitives:
64
+
65
+ - **`ultra-mcp-toolkit/sandbox`** — content-addressed (SHA256). Anonymous large payloads. Session-isolated; TTL cleanup.
66
+ - **`ultra-mcp-toolkit/page-cache`** — versioned-id (`kind + id + version`). Known keys where the version invalidates the cache (PR diff by head SHA, Confluence page by version number).
67
+
68
+ Use sandbox by default. Use page-cache only when you have a stable `(kind, id, version)` tuple and want re-fetch elision.
69
+
70
+ ## Patterns
71
+
72
+ ### List endpoint → drop inline items, keep counts
73
+
74
+ ```ts
75
+ import { paginatedListSummary } from "ultra-mcp-toolkit/trim";
76
+
77
+ const issueListSummary = (raw: unknown) =>
78
+ paginatedListSummary(raw as any, { itemPreview: false });
79
+ // → { total: 42, startAt: 0, maxResults: 50, truncated: true }
80
+ ```
81
+
82
+ The model now sees "42 results" and follows the ref for any it cares about. 50× context savings on typical paged endpoints.
83
+
84
+ ### Single-entity get → keep status fields only
85
+
86
+ ```ts
87
+ const issueSummary = (raw: unknown) => {
88
+ const r = raw as Record<string, any>;
89
+ return {
90
+ key: r.key,
91
+ url: safeHref(r.self),
92
+ ...pick(r.fields, ["summary", "status", "priority", "assignee"]),
93
+ };
94
+ };
95
+ ```
96
+
97
+ ### Mutation → minimal acknowledgement
98
+
99
+ For POST/PUT/DELETE, use the mutation-ack helper:
100
+
101
+ ```ts
102
+ import { createMutationAck } from "ultra-mcp-toolkit/mutation-ack";
103
+
104
+ const created = createMutationAck({ kind: "issue", id: r.key, url: r.self });
105
+ // → { ok: true, kind: "issue", id: "PROJ-123", url: "..." }
106
+ ```
107
+
108
+ Pairs with the dispatcher's rule: `full: true` is rejected on non-GET ops because mutation-ack already carries everything useful.
109
+
110
+ ## Don't
111
+
112
+ - **Don't fetch inside a trim.** Sync, pure, no I/O.
113
+ - **Don't drop fields the agent needs to chain.** If the next operation needs `r.id`, the summary must include it.
114
+ - **Don't return huge text bodies.** ADF, page body, PR descriptions — leave them in the ref, surface a length or summary instead.
115
+ - **Don't forget the trim key.** `op.trim = "foo"` requires `createTrimRegistry({ foo: ... })`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Scott Lepper
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,271 @@
1
+ # ultra-mcp-toolkit
2
+
3
+ **Build token-efficient [Model Context Protocol](https://modelcontextprotocol.io) (MCP) servers that fit in your AI agent's context window.**
4
+
5
+ A TypeScript toolkit for building MCP servers that don't blow up your context budget. Server-side response trimming, content-addressed disk caching, two runtime modes, and a CLI bridge — extracted from production servers benchmarked at **17× smaller responses** and **99× smaller tool listings** versus naive MCP implementations.
6
+
7
+ Used in production by [`ultra-jira-mcp`](https://github.com/scottlepp/ultra-jira-mcp), [`ultra-bitbucket-mcp`](https://github.com/scottlepp/ultra-bitbucket-mcp), and [`confluence-mcp`](https://github.com/scottlepp/confluence-mcp).
8
+
9
+ ## The problem
10
+
11
+ Naive MCP servers hand the model raw API JSON. A single Jira ticket fetch with comments can dump **270 KB (~67,000 tokens)** into your context window. Five calls and you've burned through Claude's working memory before the agent has done any actual reasoning. Tool listings alone — paid on **every** conversation — routinely run 10–40 KB.
12
+
13
+ If you've shipped an MCP server and watched it cost-spiral or drop accuracy as conversations grow, this is why.
14
+
15
+ ## The fix
16
+
17
+ Real numbers from a [production benchmark](https://github.com/scottlepp/ultra-jira-mcp/blob/main/docs/BENCHMARK.md) against a live Jira instance:
18
+
19
+ ### Tool-list cost (paid every conversation)
20
+
21
+ | approach | bytes | ~tokens | factor |
22
+ | ---------------------------- | ------: | -------: | ------------ |
23
+ | naive (one tool per op) | 38.9KB | 9,947 | 1× |
24
+ | consolidated tools | 25.1KB | 6,427 | **1.5×** |
25
+ | consolidated + filtered | ~6 KB | ~1,600 | **5×** |
26
+ | code-api mode (1 tool) | 401B | 100 | **99×** |
27
+
28
+ ### Per-call response
29
+
30
+ | scenario | naive | with toolkit | factor |
31
+ | ------------------------------ | -------: | -----------: | -----------: |
32
+ | fetch 1 simple ticket | 20.3KB | 1.2KB | **17.5×** |
33
+ | investigate rich ticket | 270.7KB | 15.5KB | **17.5×** |
34
+ | JQL search ~10 tickets | 20.5KB | 3.5KB | **5.8×** |
35
+
36
+ That rich-ticket row is the headline: **270 KB → 15.5 KB**, ~67k tokens → ~3.9k tokens, on a single investigation. The full response still lands on disk; the agent reads it via a `ref` only when it needs the detail.
37
+
38
+ ## How it works
39
+
40
+ Five design choices, all turned on by default:
41
+
42
+ 1. **Trim before the model sees it.** Responses route through allowlist projection functions; the full payload lands in a content-addressed sandbox and surfaces as a `ref:` path the agent can dereference on demand. No model-side `Read`-in-chunks loops, no asking the LLM to filter.
43
+ 2. **One manifest, many surfaces.** Operations are declared as pure data — name, verb, path template, params, trim key. The same manifest powers consolidated MCP tools, a bundled CLI binary, and **code-api mode** (one MCP tool + CLI bridge = 99× smaller tool listings).
44
+ 3. **Two cache primitives.** Content-addressed sandbox for anonymous large payloads. Versioned-id page cache for stable-keyed resources (PR diffs by head SHA, Confluence pages by version number). Both deterministic, both with TTL cleanup.
45
+ 4. **Allowlists, never denylists.** Trim functions declare what to *keep*; new API fields default to dropped. The contract between server and model stays stable when upstream APIs add noise.
46
+ 5. **Batteries included.** Pooled retry-aware HTTP transport (`undici` + 429-aware retry), atomic stream-to-disk downloads, TTL+LRU in-memory cache, Zod-validated tool dispatch with a `full: true` escape hatch — all opt-in, all consistent.
47
+
48
+ ## Quick start
49
+
50
+ ```bash
51
+ npm install ultra-mcp-toolkit
52
+ ```
53
+
54
+ ```ts
55
+ import { createSandbox } from "ultra-mcp-toolkit/sandbox";
56
+ import { createTrimRegistry } from "ultra-mcp-toolkit/trim-registry";
57
+ import { invokeOperation, type Manifest } from "ultra-mcp-toolkit/manifest";
58
+ import { bootCodeApi, createCodeApiTool } from "ultra-mcp-toolkit/code-api";
59
+ import { createCli } from "ultra-mcp-toolkit/cli";
60
+
61
+ const sandbox = createSandbox({ rootName: "my-server-mcp" });
62
+ const trimRegistry = createTrimRegistry({
63
+ thing: (raw: unknown) => /* project to compact summary */ raw,
64
+ });
65
+ const manifest: Manifest = [
66
+ { name: "thing.get", description: "fetch one", verb: "GET",
67
+ pathTemplate: "/things/{id}",
68
+ params: [{ name: "id", role: "path", required: true }],
69
+ trim: "thing" },
70
+ ];
71
+
72
+ // MCP server entrypoint (code-api mode):
73
+ const { bridge, ctx } = await bootCodeApi({
74
+ manifest, client, sandbox, trimRegistry,
75
+ cliPath: "/abs/path/to/my-server-cli/index.js",
76
+ socketEnvVar: "MY_SERVER_MCP_SOCKET",
77
+ });
78
+ const codeApiTool = createCodeApiTool({
79
+ toolName: "my_server_code_api",
80
+ cliBinaryName: "my-server-cli",
81
+ socketEnvVar: "MY_SERVER_MCP_SOCKET",
82
+ });
83
+
84
+ // Bundled CLI binary:
85
+ const cli = createCli({
86
+ cliName: "my-server-cli",
87
+ socketEnvVar: "MY_SERVER_MCP_SOCKET",
88
+ manifest, skillContent, skillSlug: "my-server",
89
+ callDirect: async (op, args) => { /* direct-mode dispatch */ },
90
+ });
91
+ process.exit(await cli.run(process.argv.slice(2)));
92
+ ```
93
+
94
+ Full walkthrough lives in the [bundled Claude Code skill](#bundled-claude-code-skill). Agents auto-load it; humans can read the markdown directly.
95
+
96
+ ## Bundled Claude Code skill
97
+
98
+ The package ships a Claude Code skill at `.claude/skills/ultra-mcp-toolkit/` — hub `SKILL.md` plus topic references covering manifest, trim, dispatcher, and server boot.
99
+
100
+ ```bash
101
+ npm run install-skill # → ~/.claude/skills/ultra-mcp-toolkit/ (user-global)
102
+ npm run install-skill -- --project # → ./.claude/skills/ultra-mcp-toolkit/ (cwd)
103
+ npm run install-skill -- --help # flags: --force, --dry-run, --print
104
+ ```
105
+
106
+ Non-Claude agents (Codex CLI, Cursor, Aider, Continue, Zed, Warp) read the skill files directly — see [AGENTS.md](AGENTS.md). The skill auto-loads in Claude Code when you mention building or extending an MCP server with this toolkit.
107
+
108
+ ## Who's it for
109
+
110
+ - **You're shipping a public MCP server** and want it to scale to long conversations without burning the user's context budget.
111
+ - **You're integrating against a verbose REST API** (Jira, Confluence, Bitbucket, Linear, Notion, GitHub, GitLab, Asana, ServiceNow, Salesforce, …) and the raw payloads are way too big.
112
+ - **You're tired of hand-rolling pagination cursors, sandbox dirs, retry loops, and tool-dispatch boilerplate** for every new server.
113
+ - **You're optimizing AI agent latency or cost** — fewer tokens in means lower per-call cost and faster time-to-first-token.
114
+
115
+ If you only need to expose two endpoints to one agent on your laptop, this is overkill. If you're shipping to users, it isn't.
116
+
117
+ ## Reference: subpath exports
118
+
119
+ Import what you need; prefer subpaths over the umbrella `ultra-mcp-toolkit` import for tree-shaking.
120
+
121
+ | Subpath | Purpose |
122
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
123
+ | `ultra-mcp-toolkit/manifest` | Operation manifest (`Operation`, `ParamSpec`) + dispatcher (`invokeOperation`, `invokeOperationRaw`). Generic over a `Client` adapter with an `ExecuteFn` hook for multi-API routing. |
124
+ | `ultra-mcp-toolkit/sandbox` | Content-addressed disk cache (SHA256 → JSON). Stores full responses out of model context; returns summary + ref. Session-isolated, TTL cleanup. |
125
+ | `ultra-mcp-toolkit/page-cache` | Versioned-id disk cache (kind + id + version → JSON). For stable-keyed resources where the version invalidates the cache. Atomic writes via tmpfile+rename. |
126
+ | `ultra-mcp-toolkit/trim` | Response-shaping helpers: `pick`, `paginatedListSummary`, `bareListSummary`, `extractNextCursor`, `safeHref`. |
127
+ | `ultra-mcp-toolkit/trim-registry` | Type-safe string-keyed registry of trim functions (`createTrimRegistry`). |
128
+ | `ultra-mcp-toolkit/tool` | Consolidated-tool dispatcher (`dispatch`, `buildInputSchema`). Includes the `full: true` escape hatch. `ToolError` alias of `DispatchError`. |
129
+ | `ultra-mcp-toolkit/code-api` | `bootCodeApi` (server startup glue), `createCodeApiTool` (single MCP tool exposed in code-api mode), and `createScriptApi`: `call(op, args)` / `readRef(ref)` for a server's script module, so loops and joins run in one Node process. Pass the module's path as `bootCodeApi({ modulePath })` and the tool response includes it. |
130
+ | `ultra-mcp-toolkit/bridge` | IPC socket bridge for code-api. `startBridge` (server), `callBridge` (client). `publishBridgeAddress` / `discoverBridgeAddress` let the CLI find a running server without the socket env var. Unix socket on POSIX, loopback TCP on Windows. |
131
+ | `ultra-mcp-toolkit/cli` | CLI scaffolding (`createCli`): argv parser, help by category (`--help` lists categories, `<category> --help` their operations, `--help --all` everything), `--select` / `--select-from=ref` output projection, install-skill subcommand, bridge dispatch, direct-mode hook. |
132
+ | `ultra-mcp-toolkit/client` | Generic `Client` interface (get/post/put/delete). Servers provide their own concrete implementations. |
133
+ | `ultra-mcp-toolkit/http-client` | `createHttpClient` — opinionated `Client` over `undici.request`. Handles redirects, basic/bearer/custom auth, 204 → `{}`. Opt-in `retry` switches to the pooled transport. |
134
+ | `ultra-mcp-toolkit/transport` | Pooled retry-aware HTTP transport. Module-level `undici.Agent` singleton (8 connections, keep-alive). 429-aware retry honoring `Retry-After`. |
135
+ | `ultra-mcp-toolkit/streaming` | `downloadToFile` (atomic stream-to-disk with sha256), `sanitizeFilename` (path-traversal safe), `guardSingleConsumption` (one-shot body wrapper). |
136
+ | `ultra-mcp-toolkit/lru` | `TtlLruCache<K, V>` — in-memory TTL + LRU for short-lived metadata (field defs, status enums). |
137
+ | `ultra-mcp-toolkit/disk-cache` | Generic `readDiskCache` / `writeDiskCache` keyed under `<rootDir>/<scope>/<sha256(key)>.json`. Corrupt files return `undefined` rather than throw. |
138
+ | `ultra-mcp-toolkit/config` | `parseToolFilterEnv` (`enabled_categories` + `disabled_actions` from env), `parseToolMode`. Server-specific env var names stay in the server. |
139
+ | `ultra-mcp-toolkit/mutation-ack` | `createMutationAck` — minimal mutation acknowledgement envelope (`{ ok, kind, id, url }`). |
140
+ | `ultra-mcp-toolkit/stdio` | `startStdioServer` — MCP stdio boot helper over a server factory. Serves both protocol revisions (2025-11-25 and 2026-07-28); hides the "don't `process.exit` after connect" + SIGINT/SIGTERM footguns. |
141
+ | `ultra-mcp-toolkit/http` | `startHttpServer` — streamable-HTTP boot helper so one process serves many clients. 2025 clients get a server per session, 2026-07-28 clients one per request, from a factory that sees the request headers; Host/Origin allowlists; `bindHeaders`. |
142
+ | `ultra-mcp-toolkit/skills` | `readSkillDir` + `checkSkillAgainstManifest`: read a skill directory and fail CI when its CLI examples name unknown operations or flags. Serving the skill is the SDK's (`loadSkills(dir).attach(mcp)`); `createCli({ skillDir })` installs the same directory, with `install-skill --check`. |
143
+ | `ultra-mcp-toolkit/confirm` | Ask the user before operations on a confirm list (`confirm_actions` from `parseToolFilterEnv`). `confirmGate` returns an `inputRequired` prompt from a tool handler (both protocol eras); code-api uses single-use tokens: the bridge refuses unconfirmed calls (`startBridge({ confirm })`), `confirmForCodeApi` asks and issues a token, the CLI passes `--confirm-token`. |
144
+ | `ultra-mcp-toolkit/schemas` | Shared Zod schemas (`positiveInt`, etc.). |
145
+ | `ultra-mcp-toolkit/agent-safety` | Defense-in-depth validators for autonomous-agent harnesses: `resolveSafePath`, `verifyResolvedRealpath`, `isProtectedPath`, `SafetyChecker`. Caller-extensible denylist + harmful/secret/shell scans. |
146
+ | `ultra-mcp-toolkit/agent-tools` | Pre-built Vercel-AI `tool({...})` factories wired through `agent-safety`: `createFileTools`, `createGitTools`, `createGitHubTools`, `createTestTools`. Optional peers: `ai`, `@octokit/rest`, `zod`. |
147
+
148
+ <details>
149
+ <summary><strong>Module deep-dives (v0.3+)</strong></summary>
150
+
151
+ ### `lru` — TTL + LRU in-memory cache
152
+
153
+ ```ts
154
+ import { TtlLruCache } from "ultra-mcp-toolkit/lru";
155
+
156
+ const fieldDefs = new TtlLruCache<string, FieldDef>({
157
+ maxSize: 500,
158
+ ttlMs: 10 * 60 * 1000,
159
+ });
160
+ fieldDefs.set("summary", def);
161
+ fieldDefs.get("summary"); // touch-on-read promotes recency
162
+ ```
163
+
164
+ ### `transport` — pooled retry-aware HTTP
165
+
166
+ ```ts
167
+ import { httpRequest, DEFAULT_RETRY, closeHttpPool } from "ultra-mcp-toolkit/transport";
168
+
169
+ const res = await httpRequest(
170
+ "https://api.example.com/v1/things",
171
+ { method: "GET", headers: { Authorization: "Bearer …" } },
172
+ DEFAULT_RETRY, // 3 retries, 500ms base, 10s cap; honors Retry-After
173
+ );
174
+
175
+ await closeHttpPool(); // on graceful shutdown
176
+ ```
177
+
178
+ Or wire it into the high-level `Client`:
179
+
180
+ ```ts
181
+ import { createHttpClient } from "ultra-mcp-toolkit/http-client";
182
+ import { DEFAULT_RETRY } from "ultra-mcp-toolkit/transport";
183
+
184
+ const client = createHttpClient({
185
+ baseUrl: "https://api.example.com",
186
+ auth: { kind: "bearer", token: process.env.TOKEN! },
187
+ retry: DEFAULT_RETRY, // omit for single-shot behavior
188
+ });
189
+ ```
190
+
191
+ ### `streaming` — stream binary downloads to disk
192
+
193
+ ```ts
194
+ import { downloadToFile } from "ultra-mcp-toolkit/streaming";
195
+
196
+ const ref = await downloadToFile({
197
+ url: attachment.contentUrl,
198
+ headers: { Authorization: basicAuth },
199
+ targetDir: sandbox.sessionCacheDir(),
200
+ filename: attachment.filename, // sanitized before writing
201
+ });
202
+ // → { absolutePath, size, sha256 }
203
+ ```
204
+
205
+ ### `disk-cache` — generic JSON K/V cache
206
+
207
+ ```ts
208
+ import { readDiskCache, writeDiskCache } from "ultra-mcp-toolkit/disk-cache";
209
+
210
+ const opts = { rootDir: sandbox.rootCacheDir(), scope: "tenant",
211
+ ttlMs: 24 * 60 * 60 * 1000 };
212
+ const cached = await readDiskCache<{ cloudId: string }>(opts, host);
213
+ if (!cached) {
214
+ const fetched = await fetchTenantInfo(host);
215
+ await writeDiskCache(opts, host, fetched);
216
+ }
217
+ ```
218
+
219
+ ### `tool/dispatcher` — `full: true` escape hatch
220
+
221
+ The dispatcher peels off `full: true` before per-action Zod validation and (for read-shaped GET ops) routes through `invokeOperationRaw` so the agent receives the untrimmed response — useful when the default summary drops content the caller wants. Mutation verbs reject `full: true` explicitly.
222
+
223
+ ```ts
224
+ import { dispatch, FULL_META_KEY } from "ultra-mcp-toolkit/tool";
225
+
226
+ await dispatch(
227
+ myTool,
228
+ { action: "list", [FULL_META_KEY]: true, project: "ABC" },
229
+ { manifest, client, trimRegistry },
230
+ );
231
+ ```
232
+
233
+ </details>
234
+
235
+ ## Status
236
+
237
+ `v0.9` — Bridge discovery: `bootCodeApi` publishes its socket address and `createCli` finds it when the socket env var is unset or stale (host shells don't inherit it from the MCP server). Adds `<cli> status`, clearer can't-connect errors, and the `codeApiToolName` / `discovery` options. Opt out with `ULTRA_MCP_DISCOVERY=0` or `discovery: false`.
238
+
239
+ `v1.2` — Adds `confirm`: a confirm list for destructive operations. `confirmGate` for tool handlers (SDK v2 `inputRequired`, both protocol eras; clients without prompt support follow `onUnsupported`), single-use tokens for code-api (`startBridge({ confirm })`, `createCodeApiTool({ confirm: true })`, `confirmForCodeApi`, CLI `--confirm-token`), `Operation.confirm` (`message`, `typeToConfirm`), and `confirmActions` from `parseToolFilterEnv`.
240
+
241
+ `v1.3` — CLI output for agents. `<cli> --help` lists categories with their operation names, `<cli> <category> --help` that category's operations, and `--help --all` the old full listing (7.8 KB → 2.3 KB for an 86-operation manifest). `--select=a.b,c` prints only those fields of the summary, mapping through arrays, and `--select-from=ref` selects from the full response on disk instead; the `ref:` line stays last. `checkSkillAgainstManifest` accepts category help and the CLI-wide flags (`CLI_GLOBAL_FLAGS`).
242
+
243
+ `v1.4` — `preprocess` on `startBridge`, `bootCodeApi`, and `invokeAndSandbox`: rewrite args before code-api dispatch (e.g. fill a default workspace), with the same `(operation, args)` contract as the classic dispatcher's `preprocess`.
244
+
245
+ `v1.5` — `HttpClient.getText(path, query, { accept })`: override the default `Accept: text/plain` for text served under another media type (Bitbucket's step logs are `application/octet-stream` and answer 406 to `text/plain`).
246
+
247
+ `v1.6` — `createScriptApi` for code-api scripts: a server ships a small ESM module (`const api: ScriptApi = createScriptApi({ socketEnvVar, callDirect }); export const call: ScriptApi["call"] = api.call;`, annotated so declaration emit can name the types), and agents `import { call }` from it to run loops, polling, and joins in one process instead of one CLI process per call. It finds the server the way the CLI does (env var, discovery, then direct mode) and re-resolves once if the server restarted. `bootCodeApi({ modulePath })` adds the module and an example to the code-api tool response. The CLI's server lookup moved to `resolveBridgeTarget` in `/bridge`, shared by both.
248
+
249
+ `v1.1` — Adds `skills` (`readSkillDir`, `checkSkillAgainstManifest`), multi-file `install-skill` via `createCli({ skillDir })`, and `install-skill --check`. Serving uses the SDK's `loadSkills` + `attach`. `skillContent` + `skillSlug` callers are unchanged.
250
+
251
+ `v1.0` — Moves to the MCP TypeScript SDK v2 (`@modelcontextprotocol/server`). Breaking: `startStdioServer` and `startHttpServer` take a `createServer` factory that returns an `McpServer` (register tools with `registerTool` + `fromJsonSchema(buildInputSchema(tool))`). Both serve the 2025-11-25 and stateless 2026-07-28 protocol revisions. `buildInputSchema` now emits `anyOf` for fields whose type differs between actions, since v2 validates arguments against the schema. `zod` peer is `^4.2`.
252
+
253
+ `v0.8` — Adds `http` (`startHttpServer`): a streamable-HTTP boot helper so one server process can serve many MCP clients, each session with its own `Server` and its own credentials. Pure addition: no existing API changes.
254
+
255
+ `v0.5` — Bundles the toolkit's own Claude Code skill (`.claude/skills/ultra-mcp-toolkit/`) plus a `npm run install-skill` script. Pure addition: skill is opt-in, no API changes.
256
+
257
+ `v0.4` — Adds the optional `tool?: string` field to `DispatchError` / `ToolError` so catch sites can recover the consolidated tool name. Constructor arg is optional → v0.3 callers compile unchanged.
258
+
259
+ `v0.3` — Adds `lru`, `disk-cache`, `transport` (retry + pool), `streaming` (atomic download), and the `full: true` escape hatch / `ToolError` alias on the dispatcher. All v0.2 APIs preserved without breaking change.
260
+
261
+ ## Contributing
262
+
263
+ See [AGENTS.md](AGENTS.md) for build/test commands, conventions, and the cross-agent contributor guide.
264
+
265
+ ## License
266
+
267
+ MIT
268
+
269
+ ---
270
+
271
+ <sub>**Keywords:** Model Context Protocol, MCP, MCP server, MCP toolkit, Anthropic Claude, AI agent tooling, token-efficient AI, context window optimization, Claude Code, MCP TypeScript, agent infrastructure, LLM tool calling.</sub>
@@ -0,0 +1,3 @@
1
+ export * from "./safe-path.js";
2
+ export * from "./safety-checker.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/agent-safety/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from "./safe-path.js";
2
+ export * from "./safety-checker.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/agent-safety/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Single source of truth for "is this path safe for an agent to touch."
3
+ *
4
+ * Used by tools, validators, and any safety checker so every layer agrees on
5
+ * the path policy. If you find yourself adding a new write surface and
6
+ * bypassing this module, stop and route through it instead.
7
+ */
8
+ /**
9
+ * Default path patterns an agent must never read, write, stage, or commit.
10
+ *
11
+ * Match semantics: each entry is tested against (1) the basename and
12
+ * (2) any path segment of the relative POSIX path. So ".env.local" matches
13
+ * the .env.* pattern, and ".github/workflows/foo.yml" matches /^\.github$/i
14
+ * via its second segment.
15
+ *
16
+ * Callers can extend or replace this list via `SafePathOptions`.
17
+ */
18
+ export declare const DEFAULT_PROTECTED_PATH_PATTERNS: readonly RegExp[];
19
+ export interface SafePathOptions {
20
+ /** Additional patterns to treat as protected, on top of the defaults. */
21
+ extraProtected?: readonly RegExp[];
22
+ /**
23
+ * Replace the default protected list entirely. When set, `extraProtected`
24
+ * is appended to this list instead of to the defaults.
25
+ */
26
+ replaceProtected?: readonly RegExp[];
27
+ /**
28
+ * Glob-style overrides — relative POSIX paths matching any of these regexes
29
+ * are allowed through even if they also match a protected pattern.
30
+ */
31
+ allowlist?: readonly RegExp[];
32
+ }
33
+ export interface PathDecision {
34
+ safe: boolean;
35
+ /** The absolute resolved path, only set when safe. */
36
+ resolved?: string;
37
+ /** Human-readable reason; populated on rejection. */
38
+ reason?: string;
39
+ }
40
+ /**
41
+ * Resolve a user-supplied path inside `workingDir` and validate it. Rejects:
42
+ * - absolute paths
43
+ * - paths containing `..` segments
44
+ * - paths that, after resolution, escape `workingDir`
45
+ * - paths matching the active protected pattern list (unless allowlisted)
46
+ *
47
+ * Symlinks are checked separately via `verifyResolvedRealpath` once the file
48
+ * exists — call that from `readFile`/`writeFile` after this returns.
49
+ */
50
+ export declare function resolveSafePath(workingDir: string, requested: string, options?: SafePathOptions): PathDecision;
51
+ /**
52
+ * After a file is resolved, verify its realpath stays inside `workingDir`.
53
+ * Catches symlinks the agent or attacker might have planted that point at
54
+ * `/etc/passwd`, `~/.ssh/id_rsa`, etc.
55
+ *
56
+ * Call AFTER `resolveSafePath`, only on paths that exist on disk. Missing
57
+ * files (e.g. on first-write) are considered safe — there's nothing to
58
+ * symlink-attack yet.
59
+ */
60
+ export declare function verifyResolvedRealpath(workingDir: string, resolvedAbs: string, options?: SafePathOptions): Promise<PathDecision>;
61
+ /**
62
+ * Pure pattern check — does a relative POSIX-style path match any protected
63
+ * pattern? Exposed so callers can validate paths from PR file lists or
64
+ * similar without going through filesystem resolution.
65
+ */
66
+ export declare function isProtectedPath(relPath: string, options?: SafePathOptions): boolean;
67
+ //# sourceMappingURL=safe-path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-path.d.ts","sourceRoot":"","sources":["../../src/agent-safety/safe-path.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AAEH;;;;;;;;;GASG;AACH,eAAO,MAAM,+BAA+B,EAAE,SAAS,MAAM,EAmC5D,CAAC;AAEF,MAAM,WAAW,eAAe;IAC9B,yEAAyE;IACzE,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;;OAGG;IACH,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC/B;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,OAAO,CAAC;IACd,sDAAsD;IACtD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAUD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,eAAe,GACxB,YAAY,CAmCd;AAED;;;;;;;;GAQG;AACH,wBAAsB,sBAAsB,CAC1C,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,YAAY,CAAC,CAsBvB;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAmBnF"}
@@ -0,0 +1,157 @@
1
+ import * as path from "path";
2
+ import * as fs from "fs/promises";
3
+ /**
4
+ * Single source of truth for "is this path safe for an agent to touch."
5
+ *
6
+ * Used by tools, validators, and any safety checker so every layer agrees on
7
+ * the path policy. If you find yourself adding a new write surface and
8
+ * bypassing this module, stop and route through it instead.
9
+ */
10
+ /**
11
+ * Default path patterns an agent must never read, write, stage, or commit.
12
+ *
13
+ * Match semantics: each entry is tested against (1) the basename and
14
+ * (2) any path segment of the relative POSIX path. So ".env.local" matches
15
+ * the .env.* pattern, and ".github/workflows/foo.yml" matches /^\.github$/i
16
+ * via its second segment.
17
+ *
18
+ * Callers can extend or replace this list via `SafePathOptions`.
19
+ */
20
+ export const DEFAULT_PROTECTED_PATH_PATTERNS = [
21
+ // Secrets / credentials
22
+ /^\.env$/i,
23
+ /^\.env\..*/i,
24
+ /credentials/i,
25
+ /secrets?/i,
26
+ /\.pem$/i,
27
+ /\.key$/i,
28
+ /\.p12$/i,
29
+ /\.pfx$/i,
30
+ /id_rsa/i,
31
+ /id_ed25519/i,
32
+ /^\.ssh$/i,
33
+ /^\.aws$/i,
34
+ /^\.npmrc$/i,
35
+ /^\.gitconfig$/i,
36
+ // CI/CD — the agent must not be able to grant itself more permissions or
37
+ // disable safety checks by editing the workflows that govern it.
38
+ /^\.github$/i,
39
+ // Dependency manifests / lockfiles — package upgrades go through Dependabot,
40
+ // not an autonomous agent.
41
+ /^package-lock\.json$/i,
42
+ /^npm-shrinkwrap\.json$/i,
43
+ /^yarn\.lock$/i,
44
+ /^pnpm-lock\.yaml$/i,
45
+ /^bun\.lockb$/i,
46
+ // The agent's own code. Letting the agent rewrite its safety layer or
47
+ // tools would defeat every other control here.
48
+ /^scripts$/i,
49
+ // VCS internals
50
+ /^\.git$/i,
51
+ ];
52
+ function protectedListFor(options) {
53
+ const base = options?.replaceProtected ?? DEFAULT_PROTECTED_PATH_PATTERNS;
54
+ if (options?.extraProtected && options.extraProtected.length > 0) {
55
+ return [...base, ...options.extraProtected];
56
+ }
57
+ return base;
58
+ }
59
+ /**
60
+ * Resolve a user-supplied path inside `workingDir` and validate it. Rejects:
61
+ * - absolute paths
62
+ * - paths containing `..` segments
63
+ * - paths that, after resolution, escape `workingDir`
64
+ * - paths matching the active protected pattern list (unless allowlisted)
65
+ *
66
+ * Symlinks are checked separately via `verifyResolvedRealpath` once the file
67
+ * exists — call that from `readFile`/`writeFile` after this returns.
68
+ */
69
+ export function resolveSafePath(workingDir, requested, options) {
70
+ if (typeof requested !== "string" || requested.length === 0) {
71
+ return { safe: false, reason: "Path must be a non-empty string" };
72
+ }
73
+ if (path.isAbsolute(requested)) {
74
+ return { safe: false, reason: `Absolute paths are not permitted: ${requested}` };
75
+ }
76
+ const normalized = path.normalize(requested);
77
+ const segments = normalized.split(path.sep);
78
+ if (segments.some((s) => s === "..")) {
79
+ return { safe: false, reason: `Path escapes working directory: ${requested}` };
80
+ }
81
+ const resolved = path.resolve(workingDir, normalized);
82
+ const resolvedRel = path.relative(workingDir, resolved);
83
+ if (resolvedRel === "" || resolvedRel.startsWith("..") || path.isAbsolute(resolvedRel)) {
84
+ if (resolvedRel === "") {
85
+ return { safe: false, reason: "Path resolves to the working directory itself" };
86
+ }
87
+ return {
88
+ safe: false,
89
+ reason: `Path escapes working directory: ${requested}`,
90
+ };
91
+ }
92
+ if (isProtectedPath(resolvedRel, options)) {
93
+ return {
94
+ safe: false,
95
+ reason: `Path is protected from agent modification: ${resolvedRel}`,
96
+ };
97
+ }
98
+ return { safe: true, resolved };
99
+ }
100
+ /**
101
+ * After a file is resolved, verify its realpath stays inside `workingDir`.
102
+ * Catches symlinks the agent or attacker might have planted that point at
103
+ * `/etc/passwd`, `~/.ssh/id_rsa`, etc.
104
+ *
105
+ * Call AFTER `resolveSafePath`, only on paths that exist on disk. Missing
106
+ * files (e.g. on first-write) are considered safe — there's nothing to
107
+ * symlink-attack yet.
108
+ */
109
+ export async function verifyResolvedRealpath(workingDir, resolvedAbs, options) {
110
+ let real;
111
+ try {
112
+ real = await fs.realpath(resolvedAbs);
113
+ }
114
+ catch {
115
+ return { safe: true, resolved: resolvedAbs };
116
+ }
117
+ const realRoot = await fs.realpath(workingDir).catch(() => workingDir);
118
+ const rel = path.relative(realRoot, real);
119
+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) {
120
+ return {
121
+ safe: false,
122
+ reason: `Path resolves outside working directory via symlink: ${resolvedAbs} -> ${real}`,
123
+ };
124
+ }
125
+ if (isProtectedPath(rel, options)) {
126
+ return {
127
+ safe: false,
128
+ reason: `Symlink target is protected: ${resolvedAbs} -> ${real}`,
129
+ };
130
+ }
131
+ return { safe: true, resolved: real };
132
+ }
133
+ /**
134
+ * Pure pattern check — does a relative POSIX-style path match any protected
135
+ * pattern? Exposed so callers can validate paths from PR file lists or
136
+ * similar without going through filesystem resolution.
137
+ */
138
+ export function isProtectedPath(relPath, options) {
139
+ const posix = relPath.split(path.sep).join("/");
140
+ const allowlist = options?.allowlist;
141
+ if (allowlist && allowlist.some((p) => p.test(posix))) {
142
+ return false;
143
+ }
144
+ const segments = posix.split("/").filter(Boolean);
145
+ const basename = segments[segments.length - 1] ?? "";
146
+ const patterns = protectedListFor(options);
147
+ for (const pattern of patterns) {
148
+ if (pattern.test(basename))
149
+ return true;
150
+ for (const seg of segments) {
151
+ if (pattern.test(seg))
152
+ return true;
153
+ }
154
+ }
155
+ return false;
156
+ }
157
+ //# sourceMappingURL=safe-path.js.map