Skip to content

Commit 1cfbdf4

Browse files
committed
tool-validate-export
1 parent be27abf commit 1cfbdf4

5 files changed

Lines changed: 137 additions & 4 deletions

File tree

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "agent-swarm-kit",
3-
"version": "1.1.142",
3+
"version": "1.1.143",
44
"description": "A TypeScript library for building orchestrated framework-agnostic multi-agent AI systems",
55
"author": {
66
"name": "Petr Tripolsky",

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,3 +289,5 @@ export const Utils = {
289289
export { validate } from "./functions/common/validate";
290290

291291
export { toJsonSchema } from "./helpers/toJsonSchema";
292+
293+
export { validateToolArguments } from "./validation/validateToolArguments";
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
2+
/**
3+
* JSON Schema type definition
4+
*/
5+
interface JsonSchema {
6+
type?: string;
7+
properties?: Record<string, any>;
8+
required?: string[];
9+
additionalProperties?: boolean;
10+
[key: string]: any;
11+
}
12+
13+
/**
14+
* Result of tool arguments validation
15+
*/
16+
export interface ValidationResult<T = any> {
17+
/** Whether validation was successful */
18+
success: boolean;
19+
/** Parsed and validated data (only present when success is true) */
20+
data?: T;
21+
/** Error message (only present when success is false) */
22+
error?: string;
23+
}
24+
25+
/**
26+
* Validates tool function arguments against a JSON schema
27+
*
28+
* @param parsedArguments - Already parsed arguments object
29+
* @param schema - JSON schema to validate against
30+
* @returns Validation result with validated data or error message
31+
*
32+
* @example
33+
* ```typescript
34+
* const result = validateToolArguments({ name: "test" }, {
35+
* type: "object",
36+
* required: ["name"],
37+
* properties: { name: { type: "string" } }
38+
* });
39+
*
40+
* if (result.success) {
41+
* console.log(result.data); // { name: "test" }
42+
* } else {
43+
* console.error(result.error);
44+
* }
45+
* ```
46+
*/
47+
export const validateToolArguments = <T = any>(
48+
parsedArguments: unknown,
49+
schema: JsonSchema
50+
): ValidationResult<T> => {
51+
// Check if arguments are null or undefined only when required fields exist
52+
if (parsedArguments == null) {
53+
if (schema?.required?.length) {
54+
return {
55+
success: false,
56+
error: "Tool call has empty arguments",
57+
};
58+
}
59+
// If no required fields, empty arguments is valid
60+
return {
61+
success: true,
62+
data: {} as T,
63+
};
64+
}
65+
66+
// Validate required fields if schema has them
67+
if (schema?.required?.length) {
68+
const argumentsObj = parsedArguments as Record<string, any>;
69+
const missingFields = schema.required.filter(
70+
(field: string) => !(field in argumentsObj)
71+
);
72+
if (missingFields.length > 0) {
73+
return {
74+
success: false,
75+
error: `Missing required fields: ${missingFields.join(", ")}`,
76+
};
77+
}
78+
}
79+
80+
return {
81+
success: true,
82+
data: parsedArguments as T,
83+
};
84+
};
85+
86+
export default validateToolArguments;

types.d.ts

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15920,6 +15920,51 @@ declare function validate(): void;
1592015920
*/
1592115921
declare const toJsonSchema: (name: string, schema: IOutlineObjectFormat) => IOutlineSchemaFormat;
1592215922

15923+
/**
15924+
* JSON Schema type definition
15925+
*/
15926+
interface JsonSchema {
15927+
type?: string;
15928+
properties?: Record<string, any>;
15929+
required?: string[];
15930+
additionalProperties?: boolean;
15931+
[key: string]: any;
15932+
}
15933+
/**
15934+
* Result of tool arguments validation
15935+
*/
15936+
interface ValidationResult<T = any> {
15937+
/** Whether validation was successful */
15938+
success: boolean;
15939+
/** Parsed and validated data (only present when success is true) */
15940+
data?: T;
15941+
/** Error message (only present when success is false) */
15942+
error?: string;
15943+
}
15944+
/**
15945+
* Validates tool function arguments against a JSON schema
15946+
*
15947+
* @param parsedArguments - Already parsed arguments object
15948+
* @param schema - JSON schema to validate against
15949+
* @returns Validation result with validated data or error message
15950+
*
15951+
* @example
15952+
* ```typescript
15953+
* const result = validateToolArguments({ name: "test" }, {
15954+
* type: "object",
15955+
* required: ["name"],
15956+
* properties: { name: { type: "string" } }
15957+
* });
15958+
*
15959+
* if (result.success) {
15960+
* console.log(result.data); // { name: "test" }
15961+
* } else {
15962+
* console.error(result.error);
15963+
* }
15964+
* ```
15965+
*/
15966+
declare const validateToolArguments: <T = any>(parsedArguments: unknown, schema: JsonSchema) => ValidationResult<T>;
15967+
1592315968
declare const Utils: {
1592415969
PersistStateUtils: typeof PersistStateUtils;
1592515970
PersistSwarmUtils: typeof PersistSwarmUtils;
@@ -15930,4 +15975,4 @@ declare const Utils: {
1593015975
PersistEmbeddingUtils: typeof PersistEmbeddingUtils;
1593115976
};
1593215977

15933-
export { Adapter, Chat, ChatInstance, Compute, type EventSource, ExecutionContextService, History, HistoryMemoryInstance, HistoryPersistInstance, type IAgentSchemaInternal, type IAgentTool, type IBaseEvent, type IBusEvent, type IBusEventContext, type IChatArgs, type IChatInstance, type IChatInstanceCallbacks, type ICompletionArgs, type ICompletionSchema, type IComputeSchema, type ICustomEvent, type IEmbeddingSchema, type IGlobalConfig, type IHistoryAdapter, type IHistoryControl, type IHistoryInstance, type IHistoryInstanceCallbacks, type IIncomingMessage, type ILoggerAdapter, type ILoggerInstance, type ILoggerInstanceCallbacks, type IMCPSchema, type IMCPTool, type IMCPToolCallDto, type IMakeConnectionConfig, type IMakeDisposeParams, type IModelMessage, type INavigateToAgentParams, type INavigateToTriageParams, type IOutgoingMessage, type IOutlineFormat, type IOutlineHistory, type IOutlineMessage, type IOutlineObjectFormat, type IOutlineResult, type IOutlineSchema, type IOutlineSchemaFormat, type IOutlineValidationFn, type IPersistActiveAgentData, type IPersistAliveData, type IPersistBase, type IPersistEmbeddingData, type IPersistMemoryData, type IPersistNavigationStackData, type IPersistPolicyData, type IPersistStateData, type IPersistStorageData, type IPipelineSchema, type IPolicySchema, type ISessionConfig, type IStateSchema, type IStorageData, type IStorageSchema, type ISwarmSchema, type ITool, type IToolCall, type IWikiSchema, Logger, LoggerInstance, MCP, type MCPToolProperties, MethodContextService, Operator, OperatorInstance, PayloadContextService, PersistAlive, PersistBase, PersistEmbedding, PersistList, PersistMemory, PersistPolicy, PersistState, PersistStorage, PersistSwarm, Policy, type ReceiveMessageFn, RoundRobin, Schema, SchemaContextService, type SendMessageFn, SharedCompute, SharedState, SharedStorage, State, Storage, type THistoryInstanceCtor, type THistoryMemoryInstance, type THistoryPersistInstance, type TLoggerInstance, type TOperatorInstance, type TPersistBase, type TPersistBaseCtor, type TPersistList, type ToolValue, Utils, addAgent, addAgentNavigation, addCompletion, addCompute, addEmbedding, addMCP, addOutline, addPipeline, addPolicy, addState, addStorage, addSwarm, addTool, addTriageNavigation, addWiki, beginContext, cancelOutput, cancelOutputForce, changeToAgent, changeToDefaultAgent, changeToPrevAgent, commitAssistantMessage, commitAssistantMessageForce, commitDeveloperMessage, commitDeveloperMessageForce, commitFlush, commitFlushForce, commitStopTools, commitStopToolsForce, commitSystemMessage, commitSystemMessageForce, commitToolOutput, commitToolOutputForce, commitToolRequest, commitToolRequestForce, commitUserMessage, commitUserMessageForce, complete, createNavigateToAgent, createNavigateToTriageAgent, disposeConnection, dumpAgent, dumpClientPerformance, dumpDocs, dumpPerfomance, dumpSwarm, emit, emitForce, event, execute, executeForce, fork, getAgent, getAgentHistory, getAgentName, getAssistantHistory, getCheckBusy, getCompletion, getCompute, getEmbeding, getLastAssistantMessage, getLastSystemMessage, getLastUserMessage, getMCP, getNavigationRoute, getPayload, getPipeline, getPolicy, getRawHistory, getSessionContext, getSessionMode, getState, getStorage, getSwarm, getTool, getToolNameForModel, getUserHistory, getWiki, hasNavigation, hasSession, json, listenAgentEvent, listenAgentEventOnce, listenEvent, listenEventOnce, listenExecutionEvent, listenExecutionEventOnce, listenHistoryEvent, listenHistoryEventOnce, listenPolicyEvent, listenPolicyEventOnce, listenSessionEvent, listenSessionEventOnce, listenStateEvent, listenStateEventOnce, listenStorageEvent, listenStorageEventOnce, listenSwarmEvent, listenSwarmEventOnce, makeAutoDispose, makeConnection, markOffline, markOnline, notify, notifyForce, overrideAgent, overrideCompletion, overrideCompute, overrideEmbeding, overrideMCP, overrideOutline, overridePipeline, overridePolicy, overrideState, overrideStorage, overrideSwarm, overrideTool, overrideWiki, question, questionForce, runStateless, runStatelessForce, scope, session, setConfig, startPipeline, swarm, toJsonSchema, validate };
15978+
export { Adapter, Chat, ChatInstance, Compute, type EventSource, ExecutionContextService, History, HistoryMemoryInstance, HistoryPersistInstance, type IAgentSchemaInternal, type IAgentTool, type IBaseEvent, type IBusEvent, type IBusEventContext, type IChatArgs, type IChatInstance, type IChatInstanceCallbacks, type ICompletionArgs, type ICompletionSchema, type IComputeSchema, type ICustomEvent, type IEmbeddingSchema, type IGlobalConfig, type IHistoryAdapter, type IHistoryControl, type IHistoryInstance, type IHistoryInstanceCallbacks, type IIncomingMessage, type ILoggerAdapter, type ILoggerInstance, type ILoggerInstanceCallbacks, type IMCPSchema, type IMCPTool, type IMCPToolCallDto, type IMakeConnectionConfig, type IMakeDisposeParams, type IModelMessage, type INavigateToAgentParams, type INavigateToTriageParams, type IOutgoingMessage, type IOutlineFormat, type IOutlineHistory, type IOutlineMessage, type IOutlineObjectFormat, type IOutlineResult, type IOutlineSchema, type IOutlineSchemaFormat, type IOutlineValidationFn, type IPersistActiveAgentData, type IPersistAliveData, type IPersistBase, type IPersistEmbeddingData, type IPersistMemoryData, type IPersistNavigationStackData, type IPersistPolicyData, type IPersistStateData, type IPersistStorageData, type IPipelineSchema, type IPolicySchema, type ISessionConfig, type IStateSchema, type IStorageData, type IStorageSchema, type ISwarmSchema, type ITool, type IToolCall, type IWikiSchema, Logger, LoggerInstance, MCP, type MCPToolProperties, MethodContextService, Operator, OperatorInstance, PayloadContextService, PersistAlive, PersistBase, PersistEmbedding, PersistList, PersistMemory, PersistPolicy, PersistState, PersistStorage, PersistSwarm, Policy, type ReceiveMessageFn, RoundRobin, Schema, SchemaContextService, type SendMessageFn, SharedCompute, SharedState, SharedStorage, State, Storage, type THistoryInstanceCtor, type THistoryMemoryInstance, type THistoryPersistInstance, type TLoggerInstance, type TOperatorInstance, type TPersistBase, type TPersistBaseCtor, type TPersistList, type ToolValue, Utils, addAgent, addAgentNavigation, addCompletion, addCompute, addEmbedding, addMCP, addOutline, addPipeline, addPolicy, addState, addStorage, addSwarm, addTool, addTriageNavigation, addWiki, beginContext, cancelOutput, cancelOutputForce, changeToAgent, changeToDefaultAgent, changeToPrevAgent, commitAssistantMessage, commitAssistantMessageForce, commitDeveloperMessage, commitDeveloperMessageForce, commitFlush, commitFlushForce, commitStopTools, commitStopToolsForce, commitSystemMessage, commitSystemMessageForce, commitToolOutput, commitToolOutputForce, commitToolRequest, commitToolRequestForce, commitUserMessage, commitUserMessageForce, complete, createNavigateToAgent, createNavigateToTriageAgent, disposeConnection, dumpAgent, dumpClientPerformance, dumpDocs, dumpPerfomance, dumpSwarm, emit, emitForce, event, execute, executeForce, fork, getAgent, getAgentHistory, getAgentName, getAssistantHistory, getCheckBusy, getCompletion, getCompute, getEmbeding, getLastAssistantMessage, getLastSystemMessage, getLastUserMessage, getMCP, getNavigationRoute, getPayload, getPipeline, getPolicy, getRawHistory, getSessionContext, getSessionMode, getState, getStorage, getSwarm, getTool, getToolNameForModel, getUserHistory, getWiki, hasNavigation, hasSession, json, listenAgentEvent, listenAgentEventOnce, listenEvent, listenEventOnce, listenExecutionEvent, listenExecutionEventOnce, listenHistoryEvent, listenHistoryEventOnce, listenPolicyEvent, listenPolicyEventOnce, listenSessionEvent, listenSessionEventOnce, listenStateEvent, listenStateEventOnce, listenStorageEvent, listenStorageEventOnce, listenSwarmEvent, listenSwarmEventOnce, makeAutoDispose, makeConnection, markOffline, markOnline, notify, notifyForce, overrideAgent, overrideCompletion, overrideCompute, overrideEmbeding, overrideMCP, overrideOutline, overridePipeline, overridePolicy, overrideState, overrideStorage, overrideSwarm, overrideTool, overrideWiki, question, questionForce, runStateless, runStatelessForce, scope, session, setConfig, startPipeline, swarm, toJsonSchema, validate, validateToolArguments };

0 commit comments

Comments
 (0)