Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 117 additions & 1 deletion src/tools/ProgrammaticToolCalling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,122 @@ export function unwrapToolResponse(
return result;
}

type ToolInputSchemaKind = {
object: boolean;
string: boolean;
};

function detectSchemaKind(schema: unknown): ToolInputSchemaKind {
const kind: ToolInputSchemaKind = { object: false, string: false };

if (!schema || typeof schema !== 'object') {
return kind;
}

const jsonSchemaType = (schema as { type?: unknown }).type;
if (jsonSchemaType === 'object') {
kind.object = true;
} else if (jsonSchemaType === 'string') {
kind.string = true;
} else if (Array.isArray(jsonSchemaType)) {
kind.object = jsonSchemaType.includes('object');
kind.string = jsonSchemaType.includes('string');
}

const zodDef = (schema as { _def?: unknown })._def;
if (!zodDef || typeof zodDef !== 'object') {
return kind;
}

const zodType = (zodDef as { type?: unknown; typeName?: unknown }).type;
const zodTypeName = (zodDef as { type?: unknown; typeName?: unknown })
.typeName;

if (zodType === 'object' || zodTypeName === 'ZodObject') {
kind.object = true;
} else if (zodType === 'string' || zodTypeName === 'ZodString') {
kind.string = true;
}

const innerSchema =
(
zodDef as {
innerType?: unknown;
schema?: unknown;
type?: unknown;
}
).innerType ?? (zodDef as { schema?: unknown }).schema;
if (innerSchema) {
const innerKind = detectSchemaKind(innerSchema);
kind.object ||= innerKind.object;
kind.string ||= innerKind.string;
}

const options = (zodDef as { options?: unknown }).options;
if (Array.isArray(options)) {
for (const option of options) {
const optionKind = detectSchemaKind(option);
kind.object ||= optionKind.object;
kind.string ||= optionKind.string;
}
}

return kind;
}

function getToolInputSchemaKind(tool: t.GenericTool): ToolInputSchemaKind {
if (tool.constructor.name === 'DynamicTool') {
return { object: false, string: true };
}

const schema = (tool as { schema?: unknown }).schema;
return detectSchemaKind(schema);
}

function normalizeToolInput(
input: t.PTCToolCall['input'],
tool: t.GenericTool
): t.PTCToolCall['input'] {
const schemaKind = getToolInputSchemaKind(tool);

if (typeof input !== 'string') {
if (!schemaKind.string || schemaKind.object) {
return input;
}

const inputValue = (input as { input?: unknown }).input;
if (typeof inputValue === 'string') {
return input;
}

return JSON.stringify(input);
Comment thread
danny-avila marked this conversation as resolved.
}

if (!schemaKind.object || schemaKind.string) {
return input;
}

const trimmed = input.trim();
if (!trimmed.startsWith('{')) {
return input;
}

try {
const parsed: unknown = JSON.parse(trimmed);
if (
typeof parsed === 'object' &&
parsed !== null &&
!Array.isArray(parsed)
) {
return parsed as Record<string, unknown>;
}
} catch {
return input;
}

return input;
}

/**
* Executes tools in parallel when requested by the API.
* Uses Promise.all for parallel execution, catching individual errors.
Expand All @@ -656,7 +772,7 @@ export async function executeTools(
}

try {
const result = await tool.invoke(call.input, {
const result = await tool.invoke(normalizeToolInput(call.input, tool), {
metadata: { [programmaticToolName]: true },
});

Expand Down
129 changes: 129 additions & 0 deletions src/tools/__tests__/ProgrammaticToolCalling.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,135 @@ describe('ProgrammaticToolCalling', () => {
});
});

it('parses JSON-string inputs before invoking structured tools', async () => {
const toolCalls: t.PTCToolCall[] = [
{
id: 'call_001',
name: 'get_weather',
input: '{"city":"San Francisco"}',
},
];

const results = await executeTools(toolCalls, toolMap);

expect(results).toHaveLength(1);
expect(results[0].call_id).toBe('call_001');
expect(results[0].is_error).toBe(false);
expect(results[0].result).toEqual({
temperature: 65,
condition: 'Foggy',
});
});

it('preserves JSON-looking strings for string-input tools', async () => {
const invoke = jest.fn<
(_input: unknown, _config: unknown) => Promise<unknown>
>(async (input) => input);
const customTool = {
name: 'string_tool',
schema: { type: 'string' },
invoke,
} as unknown as t.GenericTool;
const customToolMap: t.ToolMap = new Map([['string_tool', customTool]]);
const toolCalls: t.PTCToolCall[] = [
{
id: 'call_001',
name: 'string_tool',
input: '{"raw":true}',
},
];

const results = await executeTools(toolCalls, customToolMap);

expect(results[0].is_error).toBe(false);
expect(results[0].result).toBe('{"raw":true}');
expect(invoke).toHaveBeenCalledWith('{"raw":true}', {
metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },
});
});

it('stringifies object inputs before invoking string-input tools', async () => {
const invoke = jest.fn<
(_input: unknown, _config: unknown) => Promise<unknown>
>(async (input) => input);
const customTool = {
name: 'string_tool',
schema: { type: 'string' },
invoke,
} as unknown as t.GenericTool;
const customToolMap: t.ToolMap = new Map([['string_tool', customTool]]);
const toolCalls: t.PTCToolCall[] = [
{
id: 'call_001',
name: 'string_tool',
input: { raw: true },
},
];

const results = await executeTools(toolCalls, customToolMap);

expect(results[0].is_error).toBe(false);
expect(results[0].result).toBe('{"raw":true}');
expect(invoke).toHaveBeenCalledWith('{"raw":true}', {
metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },
});
});

it('preserves object inputs for mixed object-or-string schemas', async () => {
const invoke = jest.fn<
(_input: unknown, _config: unknown) => Promise<unknown>
>(async (input) => input);
const customTool = {
name: 'mixed_tool',
schema: { type: ['object', 'string'] },
invoke,
} as unknown as t.GenericTool;
const customToolMap: t.ToolMap = new Map([['mixed_tool', customTool]]);
const input = { raw: true };
const toolCalls: t.PTCToolCall[] = [
{
id: 'call_001',
name: 'mixed_tool',
input,
},
];

const results = await executeTools(toolCalls, customToolMap);

expect(results[0].is_error).toBe(false);
expect(results[0].result).toBe(input);
expect(invoke).toHaveBeenCalledWith(input, {
metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },
});
});

it('preserves JSON-looking strings for mixed object-or-string schemas', async () => {
const invoke = jest.fn<
(_input: unknown, _config: unknown) => Promise<unknown>
>(async (input) => input);
const customTool = {
name: 'mixed_tool',
schema: { type: ['object', 'string'] },
invoke,
} as unknown as t.GenericTool;
const customToolMap: t.ToolMap = new Map([['mixed_tool', customTool]]);
const toolCalls: t.PTCToolCall[] = [
{
id: 'call_001',
name: 'mixed_tool',
input: '{"raw":true}',
},
];

const results = await executeTools(toolCalls, customToolMap);

expect(results[0].is_error).toBe(false);
expect(results[0].result).toBe('{"raw":true}');
expect(invoke).toHaveBeenCalledWith('{"raw":true}', {
metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },
});
});

it('marks bash PTC inner tool invocations with bash metadata', async () => {
const invoke = jest.fn<
(_input: unknown, _config: unknown) => Promise<{ ok: boolean }>
Expand Down
4 changes: 2 additions & 2 deletions src/types/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1025,9 +1025,9 @@ export type PTCToolCall = {
id: string;
/** Tool name */
name: string;
/** Input parameters */
/** Input parameters. Some bridges may serialize object input as JSON text. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
input: Record<string, any>;
input: Record<string, any> | string;
};

/**
Expand Down
Loading