tool-input-normalization.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. createRootTraceContext,
  4. createSessionId,
  5. createToolCallId,
  6. createTurnId,
  7. } from "@zcode/contracts";
  8. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  9. import { createManualPermissionBroker } from "../src/permission/broker.js";
  10. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  11. import { createToolExecutor } from "../src/tool/executor.js";
  12. import { createToolRegistry } from "../src/tool/registry.js";
  13. import type { ToolEntry, ToolExecutionContext, ToolHandler } from "../src/tool/types.js";
  14. describe("tool execution input normalization", () => {
  15. it("safe-parses stringified JSON before tool execution when adapter input is still a string", async () => {
  16. const sessionId = createSessionId("tool-input-string");
  17. const turnId = createTurnId("tool-turn");
  18. const traceContext = createRootTraceContext({ sessionId, turnId });
  19. const registry = createToolRegistry();
  20. let capturedInput: unknown;
  21. registry.register(
  22. createToolEntry({
  23. name: "StringInputTool",
  24. runtimeInputSchema: objectRuntimeSchema((value) =>
  25. typeof value.value === "string" ? { value: value.value } : undefined,
  26. ),
  27. handler: async (input) => {
  28. capturedInput = input;
  29. return "ok";
  30. },
  31. inputSchema: {
  32. type: "object",
  33. properties: {
  34. value: { type: "string" },
  35. },
  36. required: ["value"],
  37. additionalProperties: false,
  38. },
  39. }),
  40. );
  41. const executor = createToolExecutor({
  42. emitEvent: async () => {},
  43. permissionService: new PermissionService(defaultPermissionConfig),
  44. registry,
  45. sessionId,
  46. turnId,
  47. traceContext,
  48. });
  49. const result = await executor.execute(
  50. {
  51. id: createToolCallId("string-input"),
  52. input: '{"value":"from-string"}',
  53. name: "StringInputTool",
  54. },
  55. { traceContext },
  56. );
  57. expect(result.success).toBe(true);
  58. expect(capturedInput).toEqual({ value: "from-string" });
  59. });
  60. it("applies runtime schema defaults before hooks and handlers", async () => {
  61. const sessionId = createSessionId("tool-input-defaults");
  62. const turnId = createTurnId("tool-turn");
  63. const traceContext = createRootTraceContext({ sessionId, turnId });
  64. const registry = createToolRegistry();
  65. let hookSawInput: unknown;
  66. let handlerSawInput: unknown;
  67. registry.register(
  68. createToolEntry({
  69. name: "DefaultingTool",
  70. runtimeInputSchema: objectRuntimeSchema((value) => ({
  71. flag: typeof value.flag === "boolean" ? value.flag : false,
  72. })),
  73. handler: async (input) => {
  74. handlerSawInput = input;
  75. return "ok";
  76. },
  77. inputSchema: {
  78. type: "object",
  79. properties: {
  80. flag: { type: "boolean" },
  81. },
  82. additionalProperties: false,
  83. },
  84. }),
  85. );
  86. const hookRunner = createInMemoryHookRunner({
  87. hooks: [
  88. {
  89. event: "PreToolUse",
  90. matcher: "DefaultingTool",
  91. callback: async (input) => {
  92. hookSawInput = input.toolInput;
  93. return undefined;
  94. },
  95. },
  96. ],
  97. });
  98. const executor = createToolExecutor({
  99. emitEvent: async () => {},
  100. hookRunner,
  101. permissionService: new PermissionService(defaultPermissionConfig),
  102. registry,
  103. sessionId,
  104. turnId,
  105. traceContext,
  106. });
  107. const result = await executor.execute(
  108. {
  109. id: createToolCallId("defaulting-input"),
  110. input: {},
  111. name: "DefaultingTool",
  112. },
  113. { traceContext },
  114. );
  115. expect(result.success).toBe(true);
  116. expect(hookSawInput).toEqual({ flag: false });
  117. expect(handlerSawInput).toEqual({ flag: false });
  118. });
  119. it("returns exact initial validation content for an adapter-normalized empty object", async () => {
  120. const sessionId = createSessionId("tool-input-malformed");
  121. const turnId = createTurnId("tool-turn");
  122. const traceContext = createRootTraceContext({ sessionId, turnId });
  123. const registry = createToolRegistry();
  124. let handlerRan = false;
  125. registry.register(
  126. createToolEntry({
  127. name: "AskUserQuestion",
  128. runtimeInputSchema: objectRuntimeSchema((value) =>
  129. Array.isArray(value.questions) ? { questions: value.questions } : undefined,
  130. ),
  131. handler: async () => {
  132. handlerRan = true;
  133. return "ok";
  134. },
  135. inputSchema: {
  136. type: "object",
  137. properties: {
  138. questions: { type: "array" },
  139. },
  140. required: ["questions"],
  141. additionalProperties: false,
  142. },
  143. }),
  144. );
  145. const executor = createToolExecutor({
  146. emitEvent: async () => {},
  147. permissionService: new PermissionService(defaultPermissionConfig),
  148. registry,
  149. sessionId,
  150. turnId,
  151. traceContext,
  152. });
  153. const result = await executor.execute(
  154. {
  155. id: createToolCallId("malformed-input"),
  156. input: {},
  157. name: "AskUserQuestion",
  158. },
  159. { traceContext },
  160. );
  161. expect(result.success).toBe(false);
  162. expect(result).toMatchObject({
  163. toolCallId: createToolCallId("malformed-input"),
  164. toolName: "AskUserQuestion",
  165. });
  166. expect(result.error?.message).toBe("Tool input failed inputSchema validation");
  167. expect(result.modelContent).toBe(
  168. [
  169. "<tool_use_error>InputValidationError: AskUserQuestion failed due to the following issue:",
  170. "The required parameter `questions` is missing</tool_use_error>",
  171. ].join("\n"),
  172. );
  173. expect(handlerRan).toBe(false);
  174. });
  175. it("uses the canonical tool name in initial validation content", async () => {
  176. const sessionId = createSessionId("tool-input-alias-validation");
  177. const turnId = createTurnId("tool-turn");
  178. const traceContext = createRootTraceContext({ sessionId, turnId });
  179. const registry = createToolRegistry();
  180. registry.register(
  181. createToolEntry({
  182. aliases: ["validation_alias"],
  183. name: "CanonicalValidationTool",
  184. runtimeInputSchema: objectRuntimeSchema((value) =>
  185. typeof value.value === "string" ? { value: value.value } : undefined,
  186. ),
  187. handler: async () => "ok",
  188. inputSchema: {
  189. type: "object",
  190. properties: {
  191. value: { type: "string" },
  192. },
  193. required: ["value"],
  194. additionalProperties: false,
  195. },
  196. }),
  197. );
  198. const executor = createToolExecutor({
  199. emitEvent: async () => {},
  200. permissionService: new PermissionService(defaultPermissionConfig),
  201. registry,
  202. sessionId,
  203. turnId,
  204. traceContext,
  205. });
  206. const result = await executor.execute(
  207. {
  208. id: createToolCallId("alias-validation"),
  209. input: {},
  210. name: "validation_alias",
  211. },
  212. { traceContext },
  213. );
  214. expect(result.success).toBe(false);
  215. expect(result.toolName).toBe("CanonicalValidationTool");
  216. expect(result.modelContent).toContain(
  217. "InputValidationError: CanonicalValidationTool failed due to the following issue:",
  218. );
  219. });
  220. it("does not turn a runtime-only parser issue into a new initial rejection", async () => {
  221. const sessionId = createSessionId("tool-input-runtime-only-issue");
  222. const turnId = createTurnId("tool-turn");
  223. const traceContext = createRootTraceContext({ sessionId, turnId });
  224. const registry = createToolRegistry();
  225. let handlerSawInput: unknown;
  226. registry.register(
  227. createToolEntry({
  228. name: "RuntimeOnlyValidationTool",
  229. runtimeInputSchema: {
  230. safeParse: () => ({
  231. success: false,
  232. error: {
  233. issues: [{ code: "custom", message: "runtime-only issue", path: ["value"] }],
  234. },
  235. }),
  236. },
  237. handler: async (input) => {
  238. handlerSawInput = input;
  239. return "ok";
  240. },
  241. inputSchema: {
  242. type: "object",
  243. properties: {
  244. value: { type: "string" },
  245. },
  246. required: ["value"],
  247. additionalProperties: false,
  248. },
  249. }),
  250. );
  251. const executor = createToolExecutor({
  252. emitEvent: async () => {},
  253. permissionService: new PermissionService(defaultPermissionConfig),
  254. registry,
  255. sessionId,
  256. turnId,
  257. traceContext,
  258. });
  259. const input = { value: "accepted-by-json-schema" };
  260. const result = await executor.execute(
  261. {
  262. id: createToolCallId("runtime-only-issue"),
  263. input,
  264. name: "RuntimeOnlyValidationTool",
  265. },
  266. { traceContext },
  267. );
  268. expect(result.success).toBe(true);
  269. expect(handlerSawInput).toEqual(input);
  270. });
  271. it("re-normalizes hook-updated stringified input before permission and handler execution", async () => {
  272. const sessionId = createSessionId("tool-input-hook-update");
  273. const turnId = createTurnId("tool-turn");
  274. const traceContext = createRootTraceContext({ sessionId, turnId });
  275. const registry = createToolRegistry();
  276. let handlerSawInput: unknown;
  277. registry.register(
  278. createToolEntry({
  279. name: "HookUpdatedInputTool",
  280. runtimeInputSchema: objectRuntimeSchema((value) =>
  281. typeof value.value === "string" ? { value: value.value } : undefined,
  282. ),
  283. handler: async (input) => {
  284. handlerSawInput = input;
  285. return "ok";
  286. },
  287. inputSchema: {
  288. type: "object",
  289. properties: {
  290. value: { type: "string" },
  291. },
  292. required: ["value"],
  293. additionalProperties: false,
  294. },
  295. }),
  296. );
  297. const hookRunner = createInMemoryHookRunner({
  298. hooks: [
  299. {
  300. event: "PreToolUse",
  301. matcher: "HookUpdatedInputTool",
  302. callback: async () => ({
  303. hookSpecificOutput: {
  304. hookEventName: "PreToolUse",
  305. updatedInput: '{"value":"from-hook"}',
  306. },
  307. }),
  308. },
  309. ],
  310. });
  311. const executor = createToolExecutor({
  312. emitEvent: async () => {},
  313. hookRunner,
  314. permissionService: new PermissionService(defaultPermissionConfig),
  315. registry,
  316. sessionId,
  317. turnId,
  318. traceContext,
  319. });
  320. const result = await executor.execute(
  321. {
  322. id: createToolCallId("hook-updated-input"),
  323. input: { value: "initial" },
  324. name: "HookUpdatedInputTool",
  325. },
  326. { traceContext },
  327. );
  328. expect(result.success).toBe(true);
  329. expect(handlerSawInput).toEqual({ value: "from-hook" });
  330. });
  331. it("re-normalizes broker-modified stringified input before handler execution", async () => {
  332. const sessionId = createSessionId("tool-input-broker-update");
  333. const turnId = createTurnId("tool-turn");
  334. const traceContext = createRootTraceContext({ sessionId, turnId });
  335. const registry = createToolRegistry();
  336. const permissionBroker = createManualPermissionBroker({
  337. onRequest: (request) => {
  338. permissionBroker.resolvePermission(request.requestId, {
  339. decision: "modify",
  340. modifiedInput: '{"value":"from-broker"}',
  341. });
  342. },
  343. });
  344. let handlerSawInput: unknown;
  345. registry.register(
  346. createToolEntry({
  347. name: "BrokerUpdatedInputTool",
  348. needsApproval: true,
  349. runtimeInputSchema: objectRuntimeSchema((value) =>
  350. typeof value.value === "string" ? { value: value.value } : undefined,
  351. ),
  352. handler: async (input) => {
  353. handlerSawInput = input;
  354. return "ok";
  355. },
  356. inputSchema: {
  357. type: "object",
  358. properties: {
  359. value: { type: "string" },
  360. },
  361. required: ["value"],
  362. additionalProperties: false,
  363. },
  364. }),
  365. );
  366. const executor = createToolExecutor({
  367. emitEvent: async () => {},
  368. permissionBroker,
  369. permissionService: new PermissionService(defaultPermissionConfig),
  370. registry,
  371. sessionId,
  372. turnId,
  373. traceContext,
  374. });
  375. const result = await executor.execute(
  376. {
  377. id: createToolCallId("broker-updated-input"),
  378. input: { value: "initial" },
  379. name: "BrokerUpdatedInputTool",
  380. },
  381. { traceContext },
  382. );
  383. expect(result.success).toBe(true);
  384. expect(handlerSawInput).toEqual({ value: "from-broker" });
  385. });
  386. it("does not apply initial validation content to broker-modified input", async () => {
  387. const sessionId = createSessionId("tool-input-broker-invalid");
  388. const turnId = createTurnId("tool-turn");
  389. const traceContext = createRootTraceContext({ sessionId, turnId });
  390. const registry = createToolRegistry();
  391. const permissionBroker = createManualPermissionBroker({
  392. onRequest: (request) => {
  393. permissionBroker.resolvePermission(request.requestId, {
  394. decision: "modify",
  395. modifiedInput: {},
  396. });
  397. },
  398. });
  399. registry.register(
  400. createToolEntry({
  401. name: "BrokerInvalidInputTool",
  402. needsApproval: true,
  403. runtimeInputSchema: objectRuntimeSchema((value) =>
  404. typeof value.value === "string" ? { value: value.value } : undefined,
  405. ),
  406. handler: async () => "should-not-run",
  407. inputSchema: {
  408. type: "object",
  409. properties: {
  410. value: { type: "string" },
  411. },
  412. required: ["value"],
  413. additionalProperties: false,
  414. },
  415. }),
  416. );
  417. const executor = createToolExecutor({
  418. emitEvent: async () => {},
  419. permissionBroker,
  420. permissionService: new PermissionService(defaultPermissionConfig),
  421. registry,
  422. sessionId,
  423. turnId,
  424. traceContext,
  425. });
  426. const result = await executor.execute(
  427. {
  428. id: createToolCallId("broker-invalid-input"),
  429. input: { value: "initial" },
  430. name: "BrokerInvalidInputTool",
  431. },
  432. { traceContext },
  433. );
  434. expect(result.success).toBe(false);
  435. expect(result.error?.message).toBe("Tool input failed inputSchema validation");
  436. expect(result.modelContent).toBeUndefined();
  437. });
  438. });
  439. function createToolEntry(options: {
  440. aliases?: readonly string[];
  441. name: string;
  442. handler: ToolHandler;
  443. inputSchema: ToolEntry["inputSchema"];
  444. needsApproval?: boolean;
  445. runtimeInputSchema: unknown;
  446. }): ToolEntry {
  447. const needsApproval = options.needsApproval ?? false;
  448. return {
  449. aliases: options.aliases,
  450. capability: `${options.name} test capability`,
  451. metadata: {
  452. concurrentSafe: true,
  453. destructive: false,
  454. name: options.name,
  455. needsApproval,
  456. readOnly: true,
  457. riskLevel: needsApproval ? "medium" : "low",
  458. sideEffectScope: "none",
  459. timeoutMs: 30000,
  460. },
  461. handler: async (input: unknown, context: ToolExecutionContext) =>
  462. options.handler(input, context),
  463. inputSchema: options.inputSchema,
  464. outputSchema: {
  465. type: "string",
  466. },
  467. permission: {
  468. permission: "test",
  469. reason: "test tool",
  470. riskLevel: needsApproval ? "medium" : "low",
  471. sideEffectScope: "none",
  472. needsApproval,
  473. patternSources: ["none"],
  474. denyPriority: "beforeAsk",
  475. },
  476. resultBudget: {
  477. maxInlineBytes: 100_000,
  478. maxModelBytes: 100_000,
  479. strategy: "truncate",
  480. },
  481. runtimeInputSchema: options.runtimeInputSchema,
  482. timeout: {
  483. defaultMs: 30000,
  484. maxMs: 30000,
  485. allowCallOverride: false,
  486. },
  487. cancellation: {
  488. supported: true,
  489. cleanup: "none",
  490. userVisibleMessage: "Test tool was cancelled",
  491. },
  492. trace: {
  493. required: true,
  494. propagateToAdapters: true,
  495. recordInput: "summary",
  496. recordOutput: "summary",
  497. },
  498. };
  499. }
  500. function objectRuntimeSchema<T extends Record<string, unknown>>(
  501. normalize: (value: Record<string, unknown>) => T | undefined,
  502. ): { safeParse: (value: unknown) => { success: true; data: T } | { success: false } } {
  503. return {
  504. safeParse(value) {
  505. if (!value || typeof value !== "object" || Array.isArray(value)) {
  506. return { success: false };
  507. }
  508. const normalized = normalize(value as Record<string, unknown>);
  509. if (!normalized) {
  510. return { success: false };
  511. }
  512. return {
  513. success: true,
  514. data: normalized,
  515. };
  516. },
  517. };
  518. }