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
21 changes: 20 additions & 1 deletion MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ new StackOneAPIError('Request failed', 400, { message: 'path.id is missing' }).m

## Schemas given to a model

**`toJsonSchema()` passes the served schema through**: root keywords such as `$schema`, `$defs`, `title` and `additionalProperties` reach the model as the server served them, and `required` is the served list, left out when it is missing or empty. `toOpenAI()`, `toAnthropic()`, `toOpenAIResponses()`, `toAISDK()` and `toClaudeAgentSdkTool()` fold a top-level `oneOf` / `anyOf` / `allOf`, which those APIs reject, into the root.
**`toJsonSchema()` passes the served schema through**: root keywords such as `$schema`, `$defs`, `title` and `additionalProperties` reach the model as the server served them, and `required` is the served list, left out when it is missing or empty. `toOpenAI()`, `toAnthropic()`, `toOpenAIResponses()`, `toAISDK()` and `toClaudeAgentSdk()` fold a top-level `oneOf` / `anyOf` / `allOf`, which those APIs reject, into the root.

## Hand-built tools and `ExecuteConfig`

Expand Down Expand Up @@ -329,3 +329,22 @@ const hibobTools = tools.toArray().filter((tool) => tool.connector === 'hibob');
// 3.0
const hibobTools = await toolset.fetchTools({ providers: ['hibob'] });
```

# Migrating from 3.x to 4.0

4.0 removes `BaseTool#toClaudeAgentSdkTool()`. `Tools#toClaudeAgentSdk()` keeps its name and arguments, and now returns a server whose tools carry their input schemas and receive the model's arguments.

## Claude Agent SDK

**`BaseTool#toClaudeAgentSdkTool()` is removed.** It built a definition for the Claude Agent SDK's `tool()`, which accepts only a Zod raw shape and drops a JSON schema, so a tool built from it reached Claude with no parameters. Pass the toolset to `toClaudeAgentSdk()` and hand the returned server to `mcpServers`:

```typescript
// 3.x
const definition = await tool.toClaudeAgentSdkTool();

// 4.0
const mcpServer = await tools.toClaudeAgentSdk();
// query({ prompt, options: { mcpServers: { 'stackone-tools': mcpServer } } })
```

To expose a subset of tools, filter first: `await tools.filter((tool) => tool.name.startsWith('bamboohr_')).toClaudeAgentSdk()`.
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -399,12 +399,12 @@ The catalog is cached per account scope and mode, so changing a filter never ref

`tool.toJsonSchema()` is the schema the server served, verbatim — `$schema`, `$defs`, `$ref`, `title`, `additionalProperties`, top-level `oneOf`/`anyOf`/`allOf` and every nested constraint — with the served `required` list. It is a fresh copy each call. The framework adapters start from it and change only what the provider would otherwise reject:

| Adapter | Adjustment |
| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `toJsonSchema()` | None: lossless. |
| `toOpenAI()`, `toAnthropic()`, `toClaudeAgentSdkTool()` | A top-level `oneOf`/`anyOf`/`allOf` is folded into the root: every branch's properties become root properties, and an `allOf` branch's `required` is merged in. OpenAI also rejects a top-level `enum`/`not`, so those are dropped. |
| `toOpenAIResponses()` | As above, not strict by default. `{ strict: true }` also gives the root `additionalProperties: false`, but OpenAI's strict mode additionally requires every property to be `required` and every nested object closed, which the SDK does not rewrite, so use it only for schemas that already meet that. |
| `toAISDK()` | As `toOpenAI()`, plus `additionalProperties: false` on the root. |
| Adapter | Adjustment |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `toJsonSchema()` | None: lossless. |
| `toOpenAI()`, `toAnthropic()`, `toClaudeAgentSdk()` | A top-level `oneOf`/`anyOf`/`allOf` is folded into the root: every branch's properties become root properties, and an `allOf` branch's `required` is merged in. OpenAI also rejects a top-level `enum`/`not`, so those are dropped. |
| `toOpenAIResponses()` | As above, not strict by default. `{ strict: true }` also gives the root `additionalProperties: false`, but OpenAI's strict mode additionally requires every property to be `required` and every nested object closed, which the SDK does not rewrite, so use it only for schemas that already meet that. |
| `toAISDK()` | As `toOpenAI()`, plus `additionalProperties: false` on the root. |

### Headers

Expand Down
6 changes: 3 additions & 3 deletions src/tool-optional-ai.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('BaseTool optional ai peer handling', () => {
vi.restoreAllMocks();
});

it('rejects toClaudeAgentSdkTool with StackOneError and install hint when ai is unavailable', async () => {
it('rejects toAISDK with StackOneError and install hint when ai is unavailable', async () => {
vi.doMock('./utils/try-import', () => ({
tryImport: vi.fn(async (moduleName: string, installHint: string) => {
if (moduleName === 'ai') {
Expand All @@ -37,8 +37,8 @@ describe('BaseTool optional ai peer handling', () => {
const { BaseTool } = await import('./tool');
const tool = new BaseTool('test_tool', 'Test tool', createParameters(), createExecuteConfig());

await expect(tool.toClaudeAgentSdkTool()).rejects.toBeInstanceOf(StackOneError);
await expect(tool.toClaudeAgentSdkTool()).rejects.toThrow(
await expect(tool.toAISDK()).rejects.toBeInstanceOf(StackOneError);
await expect(tool.toAISDK()).rejects.toThrow(
`ai is not installed. Please install it with: npm install ai (requires ${peerDependencies.ai})`,
);
});
Expand Down
54 changes: 36 additions & 18 deletions src/tool.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { jsonSchema } from 'ai';
import { http } from 'msw';
Expand Down Expand Up @@ -153,10 +155,6 @@ describe('BaseTool', () => {
return aiSdkJsonSchema(aiTool.inputSchema);
},
],
[
'toClaudeAgentSdkTool',
async () => aiSdkJsonSchema((await tool.toClaudeAgentSdkTool()).inputSchema),
],
];

it.each(adapters)(
Expand Down Expand Up @@ -262,20 +260,6 @@ describe('BaseTool', () => {
expect((await tool.toAISDK()).test_tool?.execution).toBeUndefined();
expect((await tool.toAISDK({ executable: false })).test_tool?.execute).toBeUndefined();
});

it('serialises a Claude Agent SDK result for the model, bytes as base64', async () => {
const tool = simpleTool();
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately bytes, not JSON
tool.execute = async () => ({ content: Buffer.from('%PDF') as never, ok: true });
const definition = await tool.toClaudeAgentSdkTool();

const result = await definition.handler({});

expect(JSON.parse(result.content[0]?.text ?? '')).toEqual({
content: Buffer.from('%PDF').toString('base64'),
ok: true,
});
});
});

describe('StackOneMcpTool as an action tool', () => {
Expand Down Expand Up @@ -756,6 +740,40 @@ describe('Tools', () => {
expect(mcpServer.name).toBe('custom');
expect(mcpServer.instance).toBeDefined();
});

it('serves the Claude Agent SDK each schema and hands the tool the model arguments', async () => {
const rich = localTool('b', richSchema);
const seen: unknown[] = [];
rich.execute = async (args) => {
seen.push(args);
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately bytes, not JSON
return { content: Buffer.from('%PDF') as never, ok: true };
};
const failing = named('c');
failing.execute = async () => {
throw new StackOneAPIError('Upstream failed', 502, null);
};
const { instance } = await new Tools([named('a'), rich, failing]).toClaudeAgentSdk();
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'test', version: '1.0.0' });
await instance.connect(serverTransport);
await client.connect(clientTransport);

const { tools } = await client.listTools();
const result = await client.callTool({ name: 'b', arguments: { employee_id: 'emp_1' } });
const failure = await client.callTool({ name: 'c', arguments: {} });
await client.close();

expect(tools.map((tool) => tool.inputSchema)).toEqual(
[named('a'), rich, failing].map((tool) => tool.toAnthropic().input_schema),
);
expect(seen).toEqual([{ employee_id: 'emp_1' }]);
expect(result).toEqual({
content: [{ type: 'text', text: JSON.stringify({ content: 'JVBERg==', ok: true }) }],
});
expect(failure).toMatchObject({ isError: true, content: [{ type: 'text' }] });
expect(JSON.stringify(failure.content)).toContain('Upstream failed');
});
});

describe('ToolParameters typing', () => {
Expand Down
98 changes: 34 additions & 64 deletions src/tool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import type { Tool as AnthropicTool } from '@anthropic-ai/sdk/resources';
import type { McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import {
CallToolRequestSchema,
ErrorCode,
ListToolsRequestSchema,
McpError,
} from '@modelcontextprotocol/sdk/types.js';
import type {
ChatCompletionFunctionTool,
ChatCompletionMessageToolCall,
Expand Down Expand Up @@ -200,44 +207,6 @@ export class BaseTool {
};
}

/**
* Convert the tool to Claude Agent SDK format.
* Returns a tool definition compatible with the Claude Agent SDK's tool() function.
*
* The schema is the one {@link toAnthropic} uses. Results are handed back as JSON text, with
* file bytes base64-encoded.
*
* @see https://docs.anthropic.com/en/docs/agents-and-tools/claude-agent-sdk
*/
async toClaudeAgentSdkTool(): Promise<{
name: string;
description: string;
inputSchema: Record<string, unknown>;
handler: (
args: Record<string, unknown>,
) => Promise<{ content: Array<{ type: 'text'; text: string }> }>;
}> {
const ai = await tryImport<typeof import('ai')>(
'ai',
`npm install ai (requires ${peerDependencies.ai})`,
);
const inputSchema = ai.jsonSchema(this.#toProviderSchema());
const execute = this.execute.bind(this);

return {
name: this.name,
description: this.description,
inputSchema,
handler: async (args: Record<string, unknown>) => {
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the SDK hands over the model's parsed JSON arguments
const result = await execute(args as JsonObject);
return {
content: [{ type: 'text' as const, text: serializeToolResult(result) }],
};
},
};
}

/**
* Convert the tool to AI SDK format.
*
Expand Down Expand Up @@ -870,35 +839,36 @@ export class Tools implements Iterable<BaseTool> {
options: ClaudeAgentSdkOptions = {},
): Promise<McpSdkServerConfigWithInstance> {
const { serverName = 'stackone-tools', serverVersion = '1.0.0' } = options;
const tools = new Map(this.#uniqueTools().map((tool) => [tool.name, tool]));

// Import the Claude Agent SDK dynamically
const claudeAgentSdk = await tryImport<typeof import('@anthropic-ai/claude-agent-sdk')>(
'@anthropic-ai/claude-agent-sdk',
`npm install @anthropic-ai/claude-agent-sdk (requires ${peerDependencies['@anthropic-ai/claude-agent-sdk']})`,
// The SDK's tool() and createSdkMcpServer() take only Zod shapes: a JSON schema is dropped,
// leaving the model no parameters and the handler the request context instead of the arguments
const server = new McpServer(
{ name: serverName, version: serverVersion },
{ capabilities: { tools: {} } },
);

// Convert all tools to Claude Agent SDK format
// We use type assertions here because the Zod types from our dynamic import
// don't perfectly match the Claude Agent SDK's expected types at compile time
const sdkTools = await Promise.all(
this.#uniqueTools().map(async (baseTool) => {
const toolDef = await baseTool.toClaudeAgentSdkTool();
return claudeAgentSdk.tool(
toolDef.name,
toolDef.description,
// oxlint-disable-next-line typescript/no-explicit-any, typescript/no-unsafe-type-assertion -- the SDK types a Zod shape; it is handed the AI SDK's JSON schema
toolDef.inputSchema as any,
toolDef.handler,
);
}),
);

// Create and return the MCP server
return claudeAgentSdk.createSdkMcpServer({
name: serverName,
version: serverVersion,
tools: sdkTools,
const listed = [...tools.values()].map((tool) => {
const { name, description, input_schema } = tool.toAnthropic();
return { name, description, inputSchema: input_schema };
});
server.server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: listed }));
server.server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
const tool = tools.get(params.name);
if (tool === undefined) {
throw new McpError(ErrorCode.InvalidParams, `Tool ${params.name} not found`);
}
try {
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the model's parsed JSON arguments
const result = await tool.execute((params.arguments ?? {}) as JsonObject);
return { content: [{ type: 'text', text: serializeToolResult(result) }] };
} catch (error) {
// A tool error goes back to the model as a result it can read, not a protocol error
const text = error instanceof Error ? error.message : String(error);
return { content: [{ type: 'text', text }], isError: true };
}
});

return { type: 'sdk', name: serverName, instance: server };
}

/**
Expand Down
Loading
Loading